如何在 rails 控制器和模板中显示 has_many?

How to display has_many in rails controller and template?

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>]  

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

@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

您也可以这样做:

显示所有反射的所有评论:

  1. reflections_controller:
def index
  @reflections = Reflection.all
end
  1. index.html.erb
<tbody>
  <% @reflections.each do |reflection| %>
    <tr>
     ...
      <td>
        <p> Comments(<%= reflection.comments.count %>) </p>
        <% reflection.comments.each do |comment| %>
          <%= comment.comment %>
        <% end %>
      </td>
        ...
      </tr>
    <% end %>
  </tbody>

显示特定反射的所有评论:

  1. 在 reflections_controller:
def show
  @reflection = Reflection.find(params[:id])
end
  1. 在show.html.erb:
...
<p>
  <strong>Comments(<%= @reflection.comments.count %>)</strong>
  <% @reflection.comments.each do |comment| %>
    <%= comment.comment %>
  <% end %>
</p>
...