如何通过连接表对Rails中的计数进行分组和排序?

时间:2013-12-24 01:04:14

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

如何将此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:错误的参数数量(2为0..1)

模型

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

1 个答案:

答案 0 :(得分:2)

尝试:

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