Chloe
Chloe

Reputation: 26294

How do I group by and order by count in Rails through a join table?

How do I translate this SQL into 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;

I tried to use

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

but it gave an error

ArgumentError: wrong number of arguments (2 for 0..1)

Models

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

Upvotes: 1

Views: 1734

Answers (1)

vee
vee

Reputation: 38645

Try:

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

Upvotes: 2

Related Questions