Forum: Ruby on Rails How to query across several tables?

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.
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2008-11-04 17:32
Hi there,

In the model situation "Book :has_many Stories", I would like to do
something like this:

Book.find(:all, :conditions => { book.story.id => @story_ids })

...which of course doesn't work with "book.story.id =>..."
(-> "undefined local variable or method 'book'")

What's the correct query syntax for such a case (where I query across
the 2 tables 'Books' and 'Stories')?

Thank you very much for your help with this!
Tom
613340c5fef56ad6fc3bf8cc617266ae?d=identicon&s=25 Andrew Porter (Guest)
on 2008-11-04 17:39
(Received via mailing list)
Tom Ha wrote:
> What's the correct query syntax for such a case (where I query across
> the 2 tables 'Books' and 'Stories')?

The magic you are looking for is :include
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-11-04 17:50
(Received via mailing list)
On 4 Nov 2008, at 16:38, Andrew Porter wrote:

>> (-> "undefined local variable or method 'book'")
>>
>> What's the correct query syntax for such a case (where I query across
>> the 2 tables 'Books' and 'Stories')?
>
> The magic you are looking for is :include

Actually it's :joins. That's something of a misuse of :include.

The keys in the hash should be qualified column names (eg :conditions
=> {'stories.id' => @story_ids}).
:joins can either be an sql fragment or an association name (or array
or hash of those)

Fred
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2008-11-04 18:14
Got it working like that - thanks very much!
This topic is locked and can not be replied to.