Rails sort tags by most used (tag.posts.count)

前端 未结 1 1684
不知归路
不知归路 2020-12-30 16:38

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 h

相关标签:
1条回答
  • 2020-12-30 17:30

    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.

    0 讨论(0)
提交回复
热议问题