snax

how to find the most popular tags

As a faithful follower of the growing up article, you now have a pretty nice custom tagging system for your app. But how do you find which tags are the most popular? After all, your tag cloud is waiting!

late for the sky

Here’s a find_popular class method for you:

class Tag < ActiveRecord::Base
  # [snip]
  def self.find_popular(args = {})
    find(:all, :select => 'tags.*, count(*) as popularity',
      :limit => args[:limit] || 10,
      :joins => "JOIN taggings ON taggings.tag_id = tags.id",
      :conditions => args[:conditions],
      :group => "taggings.tag_id",
      :order => "popularity DESC"  )
  end
end

usage note

Note that because of the count(*) as popularity clause, the returned tags will have an extra field with the number of tagged objects:

>> Tag.find_popular[0]
=> #<Tag:0x3790d18 @attributes={
  "name"=>"love",
  "id"=>"2",
  "popularity"=>"3"}
>> _.popularity
=> "3"

Pretty neat.

conclusion

Implementing this will become easier once I add custom finders to the polymorphic collection, but for now, it’s not so painful to just drop to SQL.

Thanks to defunkt for working some of this out a while back and to dbii for bugging me about an explanation.