代码之家  ›  专栏  ›  技术社区  ›  sharataka

如何显示有多少在Rails控制器和模板中?

  •  0
  • sharataka  · 技术社区  · 6 年前
    class Reflection < ApplicationRecord
        has_many :comments
    end
    
    
    class Comment < ApplicationRecord
        belongs_to :reflection
    end
    

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

    在反射的索引视图中,我希望显示每个反射拥有的注释数,并显示每个反射的注释,但我无法确定如何执行此操作。

    我试图理解反射索引控制器和模板(index.html.erb代表反射)中要包含什么代码。有什么建议吗?

    我可以使用下面的代码在反射控制器中显示单个反射的注释,但也许有更好的方法在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>]  
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Surya    6 年前

    在控制器中获取注释时,可以使用

    @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