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.
Tom H. (Guest)
on 2008-11-04 18: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
Andrew P. (Guest)
on 2008-11-04 18: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
Frederick C. (Guest)
on 2008-11-04 18:50
(Received via mailing list)
On 4 Nov 2008, at 16:38, Andrew P. 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
Tom H. (Guest)
on 2008-11-04 19:14
Got it working like that - thanks very much!
This topic is locked and can not be replied to.