Including associations with dynamic conditions

Given a school model and a student model with the school having a
has_many
relation to student:

has_many :students, :conditions => proc {
“year_id=#{send(:active_year_id)}” }

where active_year_id is a method defined in the school model, I’m
encountering an error that “active_year_id is undefined” when calling:

School.where(:active => true).includes(:students)

The condition works fine when I do, say, School.where(:id =>
10).students.

Only when I try to use includes do I get that error. Is that the right
behavior. If not, what am I doing wrong and how do I fix ?

Using Rails 3.0.9, REE 1.8.7.

On 13 Jul 2011, at 20:23, Vijay D. [email protected] wrote:

Only when I try to use includes do I get that error. Is that the right behavior.
If not, what am I doing wrong and how do I fix ?
Interpolated conditions on associations have never worked with includes,
since the point would be to load all students in one go which you can’t
do in general if each one has different conditions.
For join based includes I believe this is flat out impossible. For the
other form you might be able to crowbar it in, but it feels very tricky

Fred

Vijay D. <vijaydev.cse@…> writes:

Given a school model and a student model with the school having a has_many
relation to student:

has_many :students, :conditions => proc { “year_id=#{send
(:active_year_id)}” }

That smells like it belongs in a named scope on the School rather than
on the
relationship.

I think you can do this:

School.includes(:students).where({ :school => {:active => true, :id =>
10})

let me know if it work.

Ajit

On Thu, Jul 14, 2011 at 5:53 AM, Andrew S. [email protected]
wrote:

That smells like it belongs in a named scope on the School rather than on
the
relationship.

I want school.students to always return students belonging to the active
year. I chose this way so that I don’t need to change too much of code.

Vijayakumar D <vijaydev.cse@…> writes:

On Thu, Jul 14, 2011 at 5:53 AM, Andrew S. <andrewskegg-
[email protected]> wrote:
relationship.

I want school.students to always return students belonging to the active
year. I chose this way so that I don’t need to change too much of code.

If my ESP is working, given:

School << ActiveRecord::Base
has_many :students
belongs_to :year
end

Student << ActiveRecord::Base
belongs_to :school
belongs_to :year
end

Year << ActiveRecord::Base
has_many :schools
has_many :students
end

then finding students belonging to a particular year should be easy:

School.first.year.students

or closer to your example:

School.find(10).year.students