开发者

Rails has many through association how to order by number of children?

开发者 https://www.devze.com 2023-03-01 15:17 出处:网络
I want to create an simple menu that is ordered by how many products that are in the category(tags) Like:

I want to create an simple menu that is ordered by how many products that are in the category(tags)

Like:

Television (10)
Toothpase  (5)
Computer   (3)

My controller:

def tags
  @tags = Tag.all
end 

My view:

<% @tags.each do |tags| %>
  <li><%= tags.name %>    <%开发者_如何转开发= tags.konkurrancers.count %></li>
<% end %>

My model:

has_many :konkurrancers, :through => :tagsmenus


def tags
  @tags = Tag.all.sort_by{|t| -t.konkurrancers.count }
end

If you do this proves to be too slow you should add a counter_cache column (named children_count) to the tags table for speed, so you can then do this:

def tags
  @tags = Tag.all(:order => 'children_count DESC')
end
0

精彩评论

暂无评论...
验证码 换一张
取 消