Rails 3按顺序排序has_many:通过
我有一个应用程序,我可以列出项目并为每个项目添加标签。 模型项和标签关联如下:
class Item :taggings end class Tagging < ActiveRecord::Base belongs_to :item belongs_to :tag end class Tag :taggings end
因此,这种多对多关系允许我为每个项目设置n个标签,并且可以多次使用相同的标签。
我想列出按此标签关联的项目数排序的所有标签。 更常用的标签,首先显示。 较少使用,最后。
我怎样才能做到这一点?
问候。
Tag.joins(:taggings).select('tags.*, count(tag_id) as "tag_count"').group(:tag_id).order(' tag_count desc')
尝试它desc,asc,看看差异。
我们需要select ,要有tag_count列,我们需要tag_count列来应用它的顺序 ,rest所有直接连接和分组 。
顺便问一下,为什么不尝试这个呢?https://github.com/mbleigh/acts-as-taggable-on
你希望有更好的方法,但这对我有用(没有空白)。 假设name
是Tag模型的name属性。
foo = Tagging.select("name, count(item_id) as item_count") .joins("inner join tags on taggings.tag_id = tags.id") .group("name") .order("item_count DESC") foo.each { |r| puts "number of items tagged #{r.name}: #{r.item_count}"} -->"number of items tagged Bieber: 100" -->"number of items tagged GofT: 99"