【问题标题】:Rails 3 Order By Count on has_many :throughRails 3按has_many的计数排序:通过
【发布时间】:2012-06-12 23:53:55
【问题描述】:

我有一个应用程序,我可以在其中列出项目并为每个项目添加标签。 模型 ItemsTags 关联如下:

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

所以,这种多对多的关系让我可以为每个Item设置n个标签,同一个标签可以多次使用。

我想列出按与此标签关联的项目数排序的所有标签。更多使用的标签,首先显示。少用,最后。

我该怎么做?

问候。

【问题讨论】:

    标签: ruby ruby-on-rails-3 activerecord tagging


    【解决方案1】:
    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 列来应用 order 到它,剩下的就是直接 join分组

    顺便说一句,你为什么不试试这个https://github.com/mbleigh/acts-as-taggable-on

    【讨论】:

    • 非常感谢您的帮助。我会试试那个插件。
    • +1 摩尔。您是否知道如何通过另一层 has_many 来完成相同的查询结果:?我的问题 [stackoverflow.com/questions/19537378/…] 类似于 goo 的项目是组的成员,然后尝试按照它们在组内的使用频率顺序列出单个项目组的标签,而不是在所有项目中。谢谢!
    【解决方案2】:

    您希望有更好的方法,但这对我有用(没有空格)。假设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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-07
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多