# :include with conditions

**URL:** <https://www.ruby-forum.com/t/include-with-conditions/81951>\
**Category:** Rails\
**Created:** [January 16, 2007, 2:49pm UTC](https://www.ruby-forum.com/t/include-with-conditions/81951 "2007-01-16T14:49:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![RJRJRJ](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8491ac/32.png) [@RJRJRJ](https://www.ruby-forum.com/u/RJRJRJ)\
**Post date:** [January 16, 2007, 2:49pm UTC](https://www.ruby-forum.com/t/include-with-conditions/81951/1 "2007-01-16T14:49:16Z")

</div>

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

RJ

---

<div class="post-metadata">

**Author:** ![RJRJRJ](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8491ac/32.png) [@RJRJRJ](https://www.ruby-forum.com/u/RJRJRJ)\
**Post date:** [January 16, 2007, 3:18pm UTC](https://www.ruby-forum.com/t/include-with-conditions/81951/2 "2007-01-16T15:18:54Z")

</div>

Owner.find(:all, :include =\> :employee, :conditions =\> ‘employee.sex =  
“male”’)

should work.

Paolo

---

<div class="post-metadata">

**Author:** ![RJRJRJ](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8491ac/32.png) [@RJRJRJ](https://www.ruby-forum.com/u/RJRJRJ)\
**Post date:** [January 16, 2007, 3:27pm UTC](https://www.ruby-forum.com/t/include-with-conditions/81951/3 "2007-01-16T15:27:35Z")

</div>

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”’  
end

which lets you call:

Owner.find(:all, :include =\> :male\_employees)
