Skip to content

Instantly share code, notes, and snippets.

@oojikoo-gist
Created April 15, 2015 17:17
Show Gist options
  • Save oojikoo-gist/ddcf1cc7db1706017ba1 to your computer and use it in GitHub Desktop.
Save oojikoo-gist/ddcf1cc7db1706017ba1 to your computer and use it in GitHub Desktop.
rails: association extensions

Association Extensions

You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:

class Customer < ActiveRecord::Base
  has_many :orders do
    def find_by_order_prefix(order_number)
      find_by(region_id: order_number[0..2])
    end
  end
end

If you have an extension that should be shared by many associations, you can use a named extension module. For example:

module FindRecentExtension
  def find_recent
    where("created_at > ?", 5.days.ago)
  end
end
 
class Customer < ActiveRecord::Base
  has_many :orders, -> { extending FindRecentExtension }
end
 
class Supplier < ActiveRecord::Base
  has_many :deliveries, -> { extending FindRecentExtension }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment