【问题标题】:How do I group by and order by count in Rails through a join table?如何通过连接表在 Rails 中按计数分组和排序?
【发布时间】:2013-12-24 01:04:13
【问题描述】:

如何将此 SQL 转换为 Rails?

select tags.tag, count(*) c 
  from taggings, tags 
  where taggings.post_id = 1 and taggings.tag_id = tags.id 
  group by tag 
  order by c desc;

我尝试使用

Post.first.tags.select(:tag, "count(*) as count").group(:tag).order(count: :desc)

但它给出了一个错误

ArgumentError:参数数量错误(0..1 为 2)

型号

class Post < ActiveRecord::Base
  has_many :taggings, :dependent => :destroy
  has_many :tags, :through => :taggings


class Tagging < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  belongs_to :tag

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    试试:

    Posts.first.tags.select("tags.tag, count(1) as tag_count").group('tags.tag').order('tag_count desc')
    

    【讨论】:

    • 哇,好用。我想你必须对 Rails 如何构建 SQL 有深入的了解。我以为你可以使用 :tag 值,但我想有时你需要原始 SQL 片段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2012-03-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多