has_many :through with instance specific conditions
Is it possible to set an instance-level constraint on a has_many, :through relationship in rails 3.1?
http://guides.rubyonrails.org/association_basics.html#the-has_many-association
Something like:
Class A
has_many :c, :through => :b, :conditions => { "'c'.something_id" => @a.so开发者_如何学Cmething_id }
The documentation gives me hope with this, but it doesn't work for me:
If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes:
class Customer < ActiveRecord::Base
has_many :latest_orders, :class_name => "Order",
:conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}'
end
That gives me "unrecognized token '#'" on rails 3.1. Wondering if this functionality doesn't work anymore?
EDIT
Want to clarify why I don't think scopes are the solution. I want to be able to get from an instance of A all of the Cs that have a condition (which is based on an attribute of that instance of A). These are the only Cs that should EVER be associated with that A. To do this with scopes, I would put a scope on C that takes an argument, and then have to call it from @a with some value? I don't get why that's better than incorporating it into my has_many query directly.
Use a scope on the orders
model:
class Order < ActiveRecord::Base
belongs_to :customer
scope :latest, lambda { where('created_at > ?', 10.hours.ago) }
end
And then call it with:
@customer.orders.latest
And if you really want to use latest_orders
, you can instead add this to the Customer model:
def latest_orders
orders.where('created_at > ?', 10.hours.ago)
end
精彩评论