Adding new Methods to your association for advanced queries
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 dodef find_customer_by_order_id(order_id) o=Order.find(order_id) o.customer endend endnow in console:>>c=Customer.first#<Customer id: 1, name: "ttttttttttt", created_at: "2015-04-29 12:30:13", updated_at: "2015-05-05 10:36:06", orders_count: 1>>>c.orders.find_customer_by_order_id(2)#<Customer id: 1, name: "ttttttttttt", created_at: "2015-04-29 12:30:13", updated_at: "2015-05-05 10:36:06", orders_count: 1>
If you have an extension that should be shared by many associations, you can use a named extension module. For example:
moduleFindRecentExtensiondeffind_recentwhere("created_at > ?",5.days.ago)endendclassCustomer < ActiveRecord::Basehas_many:orders, -> { extending FindRecentExtension }endclassSupplier < ActiveRecord::Basehas_many:deliveries, -> { extending FindRecentExtension }end
Comments
Post a Comment