Goldy
Goldy

Reputation: 301

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 => :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.

Upvotes: 4

Views: 1243

Answers (1)

Shaun
Shaun

Reputation: 4799

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.

Upvotes: 4

Related Questions