I have created a simple blog application with Ruby on Rails. The applications consists of two tables, posts and comments. Comments belongs_to :post and posts has_many :comments.
I created posts table with the following columns: title:string, body:text.
I created the comments table with the following columns: body:text post_id:integer name:string email:string
In the /views/comments/index.html.erb display I would like to show a listing of all comments w/ the post title as well. Currently, the index view only displays post_id, body, name, email.
How do I replace the post_id column with the corresponding post title? Here is my code:
CommentsController Index action:
def index
@comments = Comment.all :order => "created_at DESC"
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @comments }
format.json { render :json => @comments }
format.atom
end
end
/views/comments/index.html.erb
<h1>Listing comments</h1>
<table>
<tr>
<th>Post</th>
<th>Body</th>
</tr>
<% @comments.each do |comment| %>
<tr>
<td><%=h comment.post_id %></td>
<td><%=h comment.body %></td>
<td><%=h comment.name %></td>
<td><%=h comment.email %></td>
</tr>
<% end %>
</table>
<br />
If you have 100 comments, using
comments.post.titlewith your code will result in 101 queries! See the Eager loading section on this docs page. Eager loading here will reduce it to 2.In your views, you can access the post title as
Edit: I’m using
rescue "No Post"because you have some comments withpost_id=niland some comments withpost_idthat point to posts that no longer exist.