我想显示一个按最常用顺序排列的所有帖子标签的列表。
我的 Controller 目前有:
@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(..) 来玩弄 Controller ,但似乎效果不佳。
如有任何帮助,我们将不胜感激。
谢谢。
最佳答案
您可以通过向关联添加 counter_cache 选项来告诉 Rails 自动维护使用标签的帖子计数。
在你的 Tag 模型上:
has_many :posts, :counter_cache => true
在您的 Posts 模型上:
belongs_to :tag, :counter_cache => true
通过迁移:
add_column :tags, :posts_count, :integer, :null => false, :default => 0
每当您添加带有该标签的帖子时,标签计数器都会递增 1。然后,您可以通过以下方式轻松执行订单:
Tags.order('posts_count')
可以找到有关 ActiveRecord 关联方法和选项的更多信息 here .
关于ruby-on-rails - Rails 按最常用的方式对标签进行排序 (tag.posts.count),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4701961/