# Table join

**URL:** <https://www.ruby-forum.com/t/table-join/142480>\
**Category:** Rails\
**Created:** [July 8, 2008, 12:03pm UTC](https://www.ruby-forum.com/t/table-join/142480 "2008-07-08T12:03:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jaiganez](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3ec8ea/32.png) [@jaiganez](https://www.ruby-forum.com/u/jaiganez)\
**Post date:** [July 8, 2008, 12:03pm UTC](https://www.ruby-forum.com/t/table-join/142480/1 "2008-07-08T12:03:25Z")

</div>

its my code to display list from two tables where  
books.subject\_id=subjects.id…

def list  
@subject= Subject.new  
@books = Book.find(:all)  
@subjects = Subject.find(:all)  
@bookss=Book.find(:all, :joins=\>:subject)  
end  
how can i write code in list.rhtml to display datas from two tables…  
i,ve tried like this…

\<% @books.each do |c|%\>  
\<%= c.title%\> #column from first table  
\<%=c.name%\> #column from second table…

but ,it displays error…  
“undefined method `name’ for #Book:0x4779224” any help pls…

---

<div class="post-metadata">

**Author:** ![jaiganez](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3ec8ea/32.png) [@jaiganez](https://www.ruby-forum.com/u/jaiganez)\
**Post date:** [July 8, 2008, 12:10pm UTC](https://www.ruby-forum.com/t/table-join/142480/2 "2008-07-08T12:10:42Z")

</div>

On 8 Jul 2008, at 11:03, Jai Jai wrote:

> how can i write code in list.rhtml to display datas from two tables…  
> i,ve tried like this…
> 
> \<% @books.each do |c|%\>  
> \<%= c.title%\> #column from first table  
> \<%=c.name%\> #column from second table…

Use an association. if you;ve got

class Book  
belongs\_to :subject  
end

and then

\<% @books.each do |c|%\>  
\<%= c.title%\>  
\<%=c.subject.name%\>  
\<% end %\>

You don’t need the the :joins option (you may want to use :include)

Fred

---

<div class="post-metadata">

**Author:** ![jaiganez](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3ec8ea/32.png) [@jaiganez](https://www.ruby-forum.com/u/jaiganez)\
**Post date:** [July 8, 2008, 12:19pm UTC](https://www.ruby-forum.com/t/table-join/142480/3 "2008-07-08T12:19:57Z")

</div>

yeah…it works …thak you …then if i need to select datas from two  
tables using foreign key say for eg: like

"select table1.fieldname,table2.fieldname… from table1 left join  
table2 on table2.id=table1.table\_id " how can i write code for that???  
thank u for your kind reply.
