Forum: Ruby on Rails :include with conditions.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
C728d93eb5205cf20cac0c2928b0ad62?d=identicon&s=25 RJ (Guest)
on 2007-01-16 14:49
Lets say I have an owner record which has_many employees.

If I want to eager load the employees then Owner.find(:all, :include =>
:employee) works fine and dandy.

What if I only wanted to include male employees in the eager loading for
instance?  Is there an elegant and simple way to eager load with a
condition applied to the included model?

Have google and API'd around but can't see anything obvious.

any ideas? Many thanks

10c122532c00465b809dbf9dc35806a7?d=identicon&s=25 Paolo Negri (Guest)
on 2007-01-16 15:18
(Received via mailing list)
Owner.find(:all, :include => :employee, :conditions => ' =

should work.

De271a04fe7a67b884ce75404c1dcc61?d=identicon&s=25 Chris Gernon (kabigon)
on 2007-01-16 15:27
Also, if this is called from multiple places in your application, you
can simplify it by adding associations to your model:

class Owner < ActiveRecord::Base
  has_many :employees
  has_many :male_employees,
                  :class_name => 'Employee',
                  :conditions => 'gender = "M"'
  has_many :female_employees,
                  :class_name => 'Employee',
                  :conditions => 'gender = "F"'

which lets you call:

Owner.find(:all, :include => :male_employees)
This topic is locked and can not be replied to.