On Fri, Mar 5, 2010 at 2:12 PM, Jack Shanter <[email protected]> wrote:
> Rick Denatale wrote:
>> Why not
>>
>> pages = Page.all(:include => :book)
>
> I usually need to filter by, let's say, a certain library:
>
> @pages = Page.all(
>  :select => 'pages.id, pages.no',
>  :joins => :book,
>  :conditions => "books.library_id = #{1}"
> )
>
> AR will generate:
> SELECT pages.id, pages.no FROM "pages" INNER JOIN "books" ON "books".id
> = "pages".book_id WHERE (books.library_id = 1)
>
> So the join has already been done. Wouldn't :include make a redundant
> query?

Then just change the joins to include:

Page.all(
 :include => :book,
 :conditions => ["books.library_id = ?", 1]
)

Which will both allow you to refer to the books fields in the where
clause, and return an collection of object graphs rather than page
object corrupted with fields they shouldn't have.
-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to