ruby-on-rails - 在索引 View 问题中呈现 'belongs_to"- Ruby on Rails

标签 ruby-on-rails ruby

我使用 Ruby on Rails 创建了一个简单的博客应用程序。应用程序由两个表、帖子和评论组成。评论 belongs_to :post 和帖子 has_many :comments

我创建了包含以下列的帖子表:title:stringbody: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/

相关文章:

ruby-on-rails - 嵌套属性首先保存父级

ruby-on-rails - 编辑/更新用户时重定向(有错误)

ruby - ActiveRecord bool 值返回 "f", "t"

ruby - Ruby 是否提供响应 OS X 上的 Apple 事件的机制?

ruby-on-rails - 如何使用 ruby​​ pg gem 列出 postgresql 数据库?

ruby-on-rails - 如何在 Rails 项目中将 key 文件作为参数传递

ruby-on-rails - 添加继承后检索现有的 MongoDB 集合

ruby-on-rails - RSpec 测试销毁操作

ruby-on-rails - rails 3 : Get current view's path helper?

ruby - Webmock 没有正确注册我的请求 stub