Rendering "owned_to" in index scan issue - Ruby on Rails
I have created a simple blog application with Ruby on Rails. Appendices consist of two tables, messages and comments. Comments belongs_to :post
and messages has_many :comments
.
I created a message table with the following columns: title:string
, body:text
. I created a comment table with the following columns:body:text
post_id:integer
name:string
email:string
In the display /views/comments/index.html.erb, I would like to show a list of all comments with the title of the post. Currently only post_id, body, name, email messages are shown in the index view.
How do I replace the post_id column with the appropriate header? Here is my code:
Comments Indexer Actions:
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 />
source to share
If you have 100 comments, using it comments.post.title
with your code will result in 101 requests! See the "Unwanted Downloads" section of this documentation page. Desired load here will reduce it to 2 .
def index
@comments = Comment.find(:all, :include => :post, :order => "created_at DESC")
# ...
end
In your views, you can access the post header like
<%= comment.post.title rescue "No post" %>
Edit: I am using rescue "No Post"
because you have comments with post_id
= nil
and some comments with post_id
indicate posts that no longer exist.
source to share