Acts As Taggable Plugin

The first Ruby on Rails plugin that I used was acts_as_taggable. With the acts_as_taggable plugin you can tag instances of your models in the same fashion you tag your pictures on Flickr or your bookmarks on Del.icio.us. Just to create some confusion there are two version of the the acts_as_taggable functionality. One is available as a gem while the other is a plugin. I’ll be covering the plugin here.

The taggable how-to wiki page on the rubyonrails.org has great information on how to get started with the acts_as_taggable plugin. In particular the wiki will walk you through the installation process and the creation of the tables necessary to store the tags. Once you get the plugin installed all you have to do is make your model act as taggable:

class Post < ActiveRecord::Base
  acts_as_taggable
end

In your controller you can tag a post with these siple lines of ruby code:

post = Post.find(params[:id])
post.tag_with('tag1 tag2 tag3')

To retrieve the tags for a post, as a single string, use the tag_list method. To get the tags as a list use the tags property. You can also find all posts marked with a given tag, for example:

posts = Post.find_tagged_with('tag1')

This plugin is easy to use and easy to learn from. I’ve written several ActiveRecord plugins that use this plugin as a template and now my most of my models act as taggable, commentable, versionable, rateable, etc.

Technorati Tags: , , , , , ,