我为一个类写了这个:
<% if @course.comments.exists? %>
<h2>Ratings</h2>
<% $total = 0 %>
<% @course.comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Score:</strong>
<%= comment.score %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.comment %>
</p>
<p>
<strong>Words in Comment:</strong>
<%= comment.comment.length %>
</p>
<% $total += 1%>
<%= link_to 'Destroy Rating', [comment.course, comment],
method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
<% end %>
<% else %>
<h2>No ratings available</h2>
<% end %>
<p>
<strong>Total Comments</strong>
<%= print $total %>
</p>
我尝试过放置和打印,但屏幕上没有显示任何内容。我需要让它计算<% @course.comments.each do |comment| %>
行的每次迭代。Ruby 不是我的强项,老师也不清楚如何实现这一目标。我对替代方案持开放态度。
不要使用全局,顾名思义,它们是全局的,这意味着它可能由其他请求/线程更新。
如果您尝试查找给定@course的评论总数,您可以调用 @course.comments.count。这应该给你你想要的总数。