【发布时间】:2010-04-12 15:49:42
【问题描述】:
我使用 Ruby on Rails 创建了一个简单的博客应用程序。应用程序包括两个表,posts 和 cmets。评论belongs_to :post 和帖子has_many :comments。
我创建了包含以下列的帖子表:title:string、body:text。
我用以下列创建了 cmets 表:body:textpost_id:integername:stringemail:string
在 /views/cmets/index.html.erb 显示中,我还想显示带有帖子标题的所有 cmets 的列表。目前,索引视图只显示 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/cmets/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 />
【问题讨论】:
标签: ruby-on-rails ruby