# How to join multiple DB tables in rails

**URL:** <https://www.ruby-forum.com/t/how-to-join-multiple-db-tables-in-rails/179233>\
**Category:** Rails\
**Created:** [November 20, 2009, 6:38am UTC](https://www.ruby-forum.com/t/how-to-join-multiple-db-tables-in-rails/179233 "2009-11-20T06:38:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kalpesh13131](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/c57346/32.png) [@kalpesh13131](https://www.ruby-forum.com/u/kalpesh13131)\
**Post date:** [November 20, 2009, 6:38am UTC](https://www.ruby-forum.com/t/how-to-join-multiple-db-tables-in-rails/179233/1 "2009-11-20T06:38:03Z")

</div>

I want to execute below SQL query from rails:

“select T.id, F.name, I.name as image\_name from Template T, Format F,  
Images I WHERE F.id=T.id and I.image\_id=T.image\_id;”

I tried something like this:

@result = Template.find(:all, :select =\> “Template.id, Format.name,  
Images.name as image\_name”, :joins =\> “join Format join Images on  
Format.id = Template.id and Images.image\_id = Template.image\_id”)

but it doesn’t work and also looking very ugly. Its like i am issuing  
SQL query only but with different syntax. Is there any better way?

Thanks,  
-Kalpesh

---

<div class="post-metadata">

**Author:** ![kalpesh13131](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/c57346/32.png) [@kalpesh13131](https://www.ruby-forum.com/u/kalpesh13131)\
**Post date:** [November 20, 2009, 12:10pm UTC](https://www.ruby-forum.com/t/how-to-join-multiple-db-tables-in-rails/179233/2 "2009-11-20T12:10:51Z")

</div>

Kalpesh1 Patel wrote:

> I want to execute below SQL query from rails:
> 
> “select T.id, F.name, I.name as image\_name from Template T, Format F,  
> Images I WHERE F.id=T.id and I.image\_id=T.image\_id;”
> 
> I tried something like this:
> 
> @result = Template.find(:all, :select =\> “Template.id, Format.name,  
> Images.name as image\_name”, :joins =\> “join Format join Images on  
> Format.id = Template.id and Images.image\_id = Template.image\_id”)
> 
> but it doesn’t work and also looking very ugly. Its like i am issuing  
> SQL query only but with different syntax. Is there any better way?
> 
> Thanks,  
> -Kalpesh

@result = Template.find(:all, :select =\> "Template.id, Format.name,

> Images.name as image\_name", :include =\> [:format, :image])

This assumes that you have associations like

Template  
belongs\_to :format  
belongs\_to :image

Although i’m just guessing here as your foreign key relationships are  
unusual. Usually you wouldn’t have the id in one table being a foreign  
key to id in another. Usually you would have templates.format\_id being  
a foreign key to formats.id for example.

On that subject, table names in rails are conventionally named after a  
downcased underscore pluralised version of the class name. eg class  
Template would use a table ‘templates’, class ‘LearningObjective’ would  
use table ‘learning\_objectives’ etc.
