Reputation: 26294
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)
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
Reputation: 38645
Try:
Posts.first.tags.select("tags.tag, count(1) as tag_count").group('tags.tag').order('tag_count desc')
Upvotes: 2