【问题标题】:Rails: Joining tables and grouping by countRails:连接表和按计数分组
【发布时间】:2014-11-24 10:32:53
【问题描述】:

我是 Rails 新手,目前正在开发一个标签系统,我可以为事件分配多个标签,为多个事件分配相同的标签。

标签模型如下所示:

has_many :taggings,
has_many :events, through: :taggings

Event 模型如下所示:

belongs_to :user
has_many :taggings
has_many :tags, through: :taggings

我有三个这样的表:

TAGS
id | name (string)

EVENTS
id | name (string)

TAGGINGS
id | tag_id | event_id

现在我正在尝试获取前 10 个最常用的标签。我基本上需要将标记和标记表连接在一起,并在标记中按 tag_id 分组。像这样的:

Tagging.group('tag_id').order('count_id DESC').limit(10).count('id')

但是,加入标签以便我可以获取名称字段。

【问题讨论】:

    标签: mysql ruby-on-rails rails-activerecord


    【解决方案1】:

    试试这个:

    Tag.select('tags.*, COUNT(taggings.id) AS tagging_count').
        joins(:taggings).group('tags.id').
        order('tagging_count DESC').
        limit(10).pluck(:name)
    

    【讨论】:

    • 谢谢。我不得不稍微修改一下:Tag.select('tags.*, COUNT(taggings.id) AS tagging_count')。 joins(:taggings).group('tags.id')。订单('tagging_count DESC')。限制(10)。收集(&:名称)
    • @FrankGordon :您可以在pluck(:name) 的位置做任何事情,例如:collect(&:name)map(&:name)map{|t| t.name }pluck 只是展示如何获取 name 属性的示例。我很高兴能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多