gpt4 book ai didi

ruby - Rails 3 Order By Count on has_many :through

转载 作者:数据小太阳 更新时间:2023-10-29 06:49:42 24 4
gpt4 key购买 nike

我有一个应用程序,我可以在其中列出项目并为每个项目添加标签。模型 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 标签,并且同一个标签可以多次使用。

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

我该怎么做?

问候。

最佳答案

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,剩下的就是直接加入分组

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

关于ruby - Rails 3 Order By Count on has_many :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10957025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com