在我的观点中添加评论为“评论最多”?

时间:2013-03-27 15:41:24

标签: ruby ruby-on-rails-3

我有一个Rails 3博客,其中包含has_manybelongs_to关联中的文章和评论模型。当文章评论是> 3,我应该在我的application.html.erb视图中看到它,所以我可以称之为“评论最多”。

<div class="span2">
 <%=image_tag ("Lekki_Gardens_new.gif")  %>
<br><br>
  <b><p>News update</p></b>  
  <% @articles.first(4).each do |article| %>
   <%=image_tag article.avatar_url(:lilthumb).to_s, :class=>"img-polaroid" %><br>
  <%= link_to article.name, article%><hr>
   <% end %>


</div

1 个答案:

答案 0 :(得分:3)

您可以在文章模型中使用:counter_cache选项,然后使用范围来检索评论最多的选项。

class Article < ActiveRecord::Base
  has_many :comments, counter_cache: true
  scope :most_commented, where('comments_count > 3')
end

然后在你的模板中:

<% Article.most_commented.each do |article| %>
  <% # anything you want %>
<% end %>