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)
endI 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>] 发布于 2019-08-27 04:11:53
在控制器中获取注释,您可以使用
@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。
发布于 2019-08-27 12:56:23
你也可以这样做:
显示所有反射的所有评论:
reflections_controller中def index
@reflections = Reflection.all
endindex.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>显示特定反射的所有注释:
def show
@reflection = Reflection.find(params[:id])
end...
<p>
<strong>Comments(<%= @reflection.comments.count %>)</strong>
<% @reflection.comments.each do |comment| %>
<%= comment.comment %>
<% end %>
</p>
...https://stackoverflow.com/questions/57667560
复制相似问题