Tag clouds with acts_as_taggable for different Taggable Types
So you are building a cool new web 2.0 startup and want to have the cool tagging feature. If you are using ruby on rails, you can use Acts_As_Taggable Plugin . There is a neat way to build a tag cloud explained here.
Now acts_as_taggable uses a field called taggable_type to know what object this tag is applied to. For example, you can have tags for videos, audio blah blah blah. Now you want to build a different tag cloud for each of these categories. The steps mentioned on the site do not support this. However a small modification in the SQL query used in file lib/tag.rb in the function self.tags(option={}) can achieve this. The original query is like this
def self.tags(options = {})
query = "select tags.id, name, count(*) as count"
query << " from taggings, tags"
query << " where tags.id = tag_id"
query << " group by tag_id"
query << " order by #{options[:order]}" if options[:order] != nil
query << " limit #{options[:limit]}" if options[:limit] != nil
tags = Tag.find_by_sql(query)
end
Change this to
query = "select tags.id, name, count(*) as count"
query << " from taggings, tags"
query << " where tags.id = tag_id and taggable_type = "+"'"+options[:type]+"' "
query << " group by tag_id"
query << " order by #{options[:order]}" if options[:order] != nil
query << " limit #{options[:limit]}" if options[:limit] != nil
tags = Tag.find_by_sql(query)
This adds the select based on taggable_type to the query and you can pass it as an option in the options hash. Now to build a tag cloud for audio model instead of the function call
@tags = Tag.tags(:limit => 100, :order => "name desc")
write
@tags = Tag.tags(:limit => 100, :order => "name desc",:type='Audio')
This will pull out tags only for audio and you can use this to build a tags cloud as exaplained in the post above
This is a small but useful modification. Do let me know if it can be further improved :)
Popularity: 12% [?]
-
jasswamu
-
jasswamu
-
Prateek Dayal
-
Prateek Dayal
-
http://www.pedestrianfriendly.com Sharon
-
http://www.pedestrianfriendly.com Sharon
-
http://blog.kuni.idv.tw/?p=212 海綿般的大男孩 » Blog Archive » Rails Plugin





