Take the 2-minute tour ×

Is it possible to set an instance-level constraint on a has_many, :through relationship in rails 3.1?


Something like:

Class A
    has_many :c, :through => :b, :conditions => { "'c'.something_id" => @a.something_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}'

That gives me "unrecognized token '#'" on rails 3.1. Wondering if this functionality doesn't work anymore?


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.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Use a scope on the orders model:

class Order < ActiveRecord::Base
  belongs_to :customer
  scope :latest, lambda { where('created_at > ?', 10.hours.ago) }

And then call it with:


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)
share|improve this answer
Yes. Never mix your relational clauses with conditions, even for sorting. It'll have you thinking the wrong way and that's deadly in rails! –  Michael Durrant Oct 10 '11 at 22:22
How would I replicate the has_many that I'm trying to do in my example with scopes? I got it working using a proc in my conditions, and so I'm not sure why this is better. I should mention that in my case, A really only has_many "C" where the condition holds. The other results aren't associated and it never makes sense to return them –  spike Oct 10 '11 at 22:26
You should use scopes in the way I described. Relations are between Models, and "latest_order" isn't a model, it's a scope of a model. Even though you have it working, Rails' tag line is "convention over configuration", and the convention here it to use scopes. –  bricker Oct 10 '11 at 22:28
Sorry, latest_order isn't relevant here, it's just the example from the rails guide. Look at the top one, where there's a has_many, :through and I want to apply a condition there. –  spike Oct 10 '11 at 22:30
add comment

Your Answer


