Rails 3 Order By Count on has_many :through

风流意气都作罢 提交于 2019-11-29 02:07:06
Tag.joins(:taggings).select('tags.*, count(tag_id) as "tag_count"').group(:tag_id).order(' tag_count desc')

try it desc, asc and see the difference.

We need select, to have tag_count column, and we need tag_count column to apply order to it, rest all straight forward join and grouping.

Btw, why dont you try this out https://github.com/mbleigh/acts-as-taggable-on

You'd hope there's a better way, but this worked for me (without the whitespace). Assume name is the name attribute of the Tag model.

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!