Forum: Ruby on Rails ActiveRecord: Using include with conditions

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
48af402ac1a5a73b29d0d81438aaeddb?d=identicon&s=25 Sharagoz -- (sharagoz)
on 2009-03-20 17:59
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
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-20 19:00
(Received via mailing list)
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
This topic is locked and can not be replied to.