# How to query across several tables?

**URL:** <https://www.ruby-forum.com/t/how-to-query-across-several-tables/152501>\
**Category:** Rails\
**Created:** [November 4, 2008, 5:32pm UTC](https://www.ruby-forum.com/t/how-to-query-across-several-tables/152501 "2008-11-04T17:32:06Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![tharrisx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e19adc/32.png) [@tharrisx](https://www.ruby-forum.com/u/tharrisx)\
**Post date:** [November 4, 2008, 5:32pm UTC](https://www.ruby-forum.com/t/how-to-query-across-several-tables/152501/1 "2008-11-04T17:32:06Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![tharrisx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e19adc/32.png) [@tharrisx](https://www.ruby-forum.com/u/tharrisx)\
**Post date:** [November 4, 2008, 5:39pm UTC](https://www.ruby-forum.com/t/how-to-query-across-several-tables/152501/2 "2008-11-04T17:39:45Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![tharrisx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e19adc/32.png) [@tharrisx](https://www.ruby-forum.com/u/tharrisx)\
**Post date:** [November 4, 2008, 5:50pm UTC](https://www.ruby-forum.com/t/how-to-query-across-several-tables/152501/3 "2008-11-04T17:50:19Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![tharrisx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e19adc/32.png) [@tharrisx](https://www.ruby-forum.com/u/tharrisx)\
**Post date:** [November 4, 2008, 6:14pm UTC](https://www.ruby-forum.com/t/how-to-query-across-several-tables/152501/4 "2008-11-04T18:14:16Z")

</div>

Got it working like that - thanks very much!
