我使用 Ruby on Rails 创建了一个简单的博客应用程序。应用程序由两个表、帖子和评论组成。评论 belongs_to :post
和帖子 has_many :comments
。
我创建了包含以下列的帖子表:title:string
、body:text
。
我创建了包含以下列的评论表: body:text
post_id:integer
name:string
email:string
在/views/comments/index.html.erb 显示中,我想显示所有带有帖子标题的评论列表。目前,索引 View 仅显示 post_id、body、name、email。
如何用相应的帖子标题替换 post_id 列?这是我的代码:
CommentsController 索引操作:
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 />
最佳答案
如果您有 100 条评论,在您的代码中使用 comments.post.title
将导致 101 次查询!查看Eager loading此文档页面上的部分。此处的预加载会将其减少到 2。
def index
@comments = Comment.find(:all, :include => :post, :order => "created_at DESC")
# ...
end
在您的 View 中,您可以访问帖子标题作为
<%= comment.post.title rescue "No post" %>
编辑:我正在使用 rescue "No Post"
因为你有一些评论 post_id
= nil
和一些带有 post_id
的评论指向不再存在的帖子。
关于ruby-on-rails - 在索引 View 问题中呈现 'belongs_to"- Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2623361/