首页 > 解决方案 > 如何在 Rails 控制器和模板中显示 has_many?

问题描述

class Reflection < ApplicationRecord
    has_many :comments
end


class Comment < ApplicationRecord
    belongs_to :reflection
end

我有一个应用程序,其中反射有任何评论。

在反射的索引视图中,我想显示每个反射的评论数量,并显示每个反射的评论,但我无法弄清楚如何做到这一点。

我试图了解反射索引控制器以及模板(用于反射的 index.html.erb)中包含哪些代码。有什么建议吗?

我可以在 Reflections 控制器中使用下面的代码显示单个反射的注释,但也许有更好的方法在 Rails 中执行此操作。

  def show
    @comments = Comment.where(reflection_id: @reflection.id)
  end

I tried 

  <tbody>
    <% @reflections.each do |reflection| %>
      <tr>
        <td><%= reflection.id %></td>
        <td><%= reflection.reflection %></td>
        <td><%= reflection.user_id %></td>
        <td>
//LOOPING THROUGH COMMENTS IN EACH REFLECTION
        <td><%= reflection.comments.each do |comment| %>
              <%= comment.comment %>, 
            <% end %>
        </td>
//END LOOPING THROUGH COMMENTS IN EACH REFLECTION
        </td>
        <td><%= link_to 'Show', reflection %></td>
        <td><%= link_to 'Edit', edit_reflection_path(reflection) %></td>
        <td><%= link_to 'Destroy', reflection, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>


The above yields the comment but also the objects afterwards:

    fdsafdsa, fdsacdxzdv, [#<Comment id: 8, comment: "fdsafdsa", created_at: "2019-08-27 04:13:34", updated_at: "2019-08-27 04:13:34", reflection_id: 1, user_id: 1>, #<Comment id: 9, comment: "fdsacdxzdv", created_at: "2019-08-27 04:32:36", updated_at: "2019-08-27 04:32:36", reflection_id: 1, user_id: 1>]  

标签: ruby-on-railshas-many

解决方案


在控制器中获取评论,你可以使用

@comments = @reflection.comments 然后在视图文件中显示评论,您可以循环查看@comments。

要显示视图文件中的评论数,您可以使用@comments.size

https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

要从显示中删除评论对象,请尝试以下操作。(我已经删除了=之前的循环)

 <td><%reflection.comments.each do |comment| %>
              <%= comment.comment %>, 
            <% end %>
 </td>

有关渲染的更多信息,请阅读 ruby​​ 文档 https://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB.html


推荐阅读