Rails 按最常用的方式对标签进行排序 (tag.posts.count) [英] 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.
我的控制器目前有:
@tag_list = Tag.all
我的观点有:
<% @tag_list.each do |tag| %>
<%= tag.name %>(<%= tag.posts.count %>)
<% end %>
编辑关系如下:
Tag (has_many :posts, :through => :taggings)
Tagging(belongs_to :tag and belongs_to :post)
Post(has_many :tags, :through => :taggings)
这会显示所有标签及其计数.我曾尝试使用 Tag.order(..) 来处理控制器,但似乎效果不佳.
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.
任何帮助将不胜感激.
谢谢.
推荐答案
您可以通过向关联添加 counter_cache 选项来告诉 rails 自动维护使用标签的帖子计数.
You can tell rails to automatically maintain a count of posts that use a tag by adding the counter_cache option to the association.
在您的标签模型上:
has_many :posts, :counter_cache => true
在您的帖子模型上:
belongs_to :tag, :counter_cache => true
通过迁移:
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')
有关 ActiveRecord 关联方法和选项的更多信息,请参见 这里.
More information on ActiveRecord Association methods and options can be found here.
这篇关于Rails 按最常用的方式对标签进行排序 (tag.posts.count)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!