Rails按最常用的标签排序(tag.posts.count)

我想显示所有最常用的邮件标签列表。

我的控制器目前有:

@tag_list = Tag.all 

我的观点是:

  ()  

编辑关系如下:

 Tag (has_many :posts, :through => :taggings) Tagging(belongs_to :tag and belongs_to :post) Post(has_many :tags, :through => :taggings) 

这显示了所有带有计数的标签。 我曾尝试使用Tag.order(..)来玩控制器,但似乎不太好。

任何帮助将非常感激。

谢谢。

您可以通过向关联添加counter_cache选项来告诉rails自动维护使用标记的post数。

在您的标签模型上:

 has_many :posts, :counter_cache => true 

在你的post模型上:

 belongs_to :tag, :counter_cache => true 

通过迁移:

 add_column :tags, :posts_count, :integer, :null => false, :default => 0 

每次添加带有该标签的post时,标签计数器都会增加1。 然后,您可以轻松地执行订单:

 Tags.order('posts_count') 

有关ActiveRecord关联方法和选项的更多信息,请参见此处 。