Rails sort tags by most used (tag.posts.count)
I would like to show a list of all post tags ordering them by most used.
My controller currently has:
@tag_list = Tag.all
My view has:
<% @tag_list.each do |tag| %>
<%= tag.name %>(<%= tag.posts.count %>)
<% end %>
EDIT the relationships are as follows:
Tag (has_many :posts, :through => :taggings)
Tagging(belongs_to :tag and belongs_to :post)
Post(has_many :tags, :through =&开发者_Python百科gt; :taggings)
This shows all the tags with their count. I have tried playing around with the controller using Tag.order(..) but can't seem to come good.
Any help would be much appreciated.
Thanks.
You can tell rails to automatically maintain a count of posts that use a tag by adding the counter_cache option to the association.
On your Tag model:
has_many :posts, :counter_cache => true
On your Posts model:
belongs_to :tag, :counter_cache => true
Via a migration:
add_column :tags, :posts_count, :integer, :null => false, :default => 0
Any time you add a post with that tag, the tag counter will increment by one. You can then perform your order by easily:
Tags.order('posts_count')
More information on ActiveRecord Association methods and options can be found here.
精彩评论