Rails 3 Order By Count on has_many :through

Posted by goo on Stack Overflow See other posts from Stack Overflow or by goo
Published on 2012-06-08T23:09:56Z Indexed on 2012/06/09 10:40 UTC
Read the original article Hit count: 163

I have an application where I can list Items and add tags to each Item. The models Items and Tags are associated like this:

class Item < ActiveRecord::Base
  has_many :taggings
  has_many :tags, :through => :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :item
  belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :items, :through => :taggings
end

So, this many-to-many relationship allows me to set n tags for each Item, and the same tag can be used several times.

I'd like to list all tags ordered by the number of items associated with this tag. More used tags, shows first. Less used, last.

How can I do that?

Regards.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails-3