gcs*_*str 9 ruby tagging activerecord ruby-on-rails-3
我有一个应用程序,我可以列出项目并为每个项目添加标签.模型项和标签关联如下:
class Item < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :item
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :items, :through => :taggings
end
Run Code Online (Sandbox Code Playgroud)
因此,这种多对多关系允许我为每个项目设置n个标签,并且可以多次使用相同的标签.
我想列出按此标签关联的项目数量排序的所有标签.更多使用的标签,首先显示.较少使用,最后.
我怎样才能做到这一点?
问候.
Tag.joins(:taggings).select('tags.*, count(tag_id) as "tag_count"').group(:tag_id).order(' tag_count desc')
Run Code Online (Sandbox Code Playgroud)
尝试它desc,asc,看看差异.
我们需要select,要有tag_count列,我们需要tag_count列来应用它的顺序,休息所有直接连接和分组.
顺便问一下,为什么不尝试这个呢?https://github.com/mbleigh/acts-as-taggable-on