# ActiveRecord: Using include with conditions

**URL:** <https://www.ruby-forum.com/t/activerecord-using-include-with-conditions/163470>\
**Category:** Rails\
**Created:** [March 20, 2009, 5:59pm UTC](https://www.ruby-forum.com/t/activerecord-using-include-with-conditions/163470 "2009-03-20T17:59:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sharagoz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/3ec8ea/32.png) [@sharagoz](https://www.ruby-forum.com/u/sharagoz)\
**Post date:** [March 20, 2009, 5:59pm UTC](https://www.ruby-forum.com/t/activerecord-using-include-with-conditions/163470/1 "2009-03-20T17:59:03Z")

</div>

Three models: Product, Image, Document  
Relations: A product has many images and documents.  
Images and products has a flag telling whether or not they are  
published.

I want to show a product and include only documents and images that are  
published.

I was hoping I could do this in my controller:  
@product = Product.find(params[:id], :include =\> [:images, :documents],  
:conditions =\> ‘(images.published=1 AND documents.published=1’)

That worked great as long as the product had at least one published  
image and at least one published document. If not, I would get a  
recordnotfound exception.

What I’m currently doing is this:  
@product = Product.find(params[:id], :include =\> [:images, :documents])  
@product.documents.delete\_if{|d| d.published == false}  
@product.images.delete\_if{|i| i.published == false}

This works but I’m curious if the original query can be modified to  
handle cases where a product doesnt have at least one published image  
and document. Can it?

-S

---

<div class="post-metadata">

**Author:** ![sharagoz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/3ec8ea/32.png) [@sharagoz](https://www.ruby-forum.com/u/sharagoz)\
**Post date:** [March 20, 2009, 7:00pm UTC](https://www.ruby-forum.com/t/activerecord-using-include-with-conditions/163470/2 "2009-03-20T19:00:28Z")

</div>

On 20 Mar 2009, at 16:59, Sharagoz – wrote:

> I was hoping I could do this in my controller:  
> [:images, :documents])  
> @product.documents.delete\_if{|d| d.published == false}  
> @product.images.delete\_if{|i| i.published == false}
> 
> This works but I’m curious if the original query can be modified to  
> handle cases where a product doesnt have at least one published image  
> and document. Can it?

When you do a join based include this is what happens: conditions on  
the associations can filter out their parents.

One thing that does work is  
Product.find(:all, :include =\>  
[:published\_images, :published\_documents])  
where those are associations with images & documents with the  
condition that published is true

This stuff tends to be a bit messy though.

Lastly there is very little benefit in eager loading when you only  
have 1 parent record.  
Fred
