Developer: Ruby on Rails
   DOWNLOAD
 Oracle Database XE
 Ruby OCI8 Adapter
 Ruby on Rails
 Ruby Gems
   TAGS
xe, rubyonrails, All

Tagging with Oracle and Ruby on Rails


by Matt Kern

Clear the confusion and add tags and tag clouds to your Oracle+Rails application.

Published June 2007

Social computing has taken the Internet by storm in the last few years and one of the signatures of the trend has been the notion of "tagging." While tagging is certainly not new, its latest incarnation is novel in its application—at least as far as the Web application world is concerned. Sharing tag data has allowed users of the latest round of Web applications to search for and share data like never before.

Tagging by itself won't add incredible functionality to your Rails application, but the features you build on top of tagging can add a layer of richness to your user's experience. You might find yourself quickly becoming addicted to new features that leverage your simple little strings.

This article will show you just how easy it is to add tag functionality to your site through the use of the acts_as_taggable_on_steroids plugin.

Confusion Abounds

Believe it or not, the hardest part of adding tags to your Rails application is figuring out which of the libraries to use. There are a number of competing implementations of the acts_as_taggable idea. At the time of writing there are at least four advertised ways to implement tagging in a Rails application:

  • acts_as_taggable gem
  • acts_as_taggable plugin
  • acts_as_taggable_on_steroids plugin
  • has_many_polymorphs plugin

Let's review each of these options and try to shed some light on what can be a very confusing situation.

acts_as_taggable gem. This gem was the first of the implementations written for Rails and as such, it's really meant for older versions of 1.0. It will work on the current Rails versions (1.1, 1.2 and Edge Rails—"Edge Rails" being a fancy term for running the very latest, or HEAD, version of Rails). The Gem has one really significant weakness that makes it a non-starter for usage in your Rails application. It requires a separate join table for every model you want to tag. If you're looking to simply tag one model, though, this may be the simplest solution. You can tag more than one model, but you're required to create a separate join table and association for each model tagged, adding a significant amount of overhead.

acts_as_taggable plugin. This plugin (as opposed to the gem) was written by David Heinemeier Hanson, the creator of Rails. It was implemented using some of the more advanced features available in the newer versions of Rails like :has_many_through and polymorphic associations. It's a good start, but Hanson himself admits that the plugin is only half-baked and the core Rails team has opted not to apply many of the patches that have been submitted by the Rails community. (There's even a reported SQL injection vulnerability that, to my knowledge, has not been patched in the official releases!) This is probably the easiest implementation to install and use, though, so it may be something you want to look at. It's accessible directly through the Rails SVN server, so all that's needed is to call

$ script/plugin install acts_as_taggable        

Unfortunately, according to the Rails core developers, the plugin was intended only as a proof of concept and there are quite a few issues with it.

acts_as_taggable_on_steroids plugin. Although the name of the plugin sounds like it should be additional functionality built atop the original acts_as_taggable plugin, it's really not. It is a rewrite of the original plugin and it does add tests and some additional functionality. And adding to the extreme confusion is that the original author of the acts_as_taggable gem posted a blog entry called "Tagging on Steroids with Rails". Whew! (We'll focus on this plugin, since the "official" Rails plugin isn't intended for production use.)

has_many_polymorphs plugin. A relative newcomer on the block, has_many_polymorphs is a more abstract, very powerful plugin that can be used for adding tags to your model, although it's not built specifically for that purpose. I'll explain some of the problems that the has_many_polymorphs plugin solves later; for now, we'll favor the acts_as_taggable_on_steroids due to its more straightforward nature and ease of use for developers new to Rails. Polymorphic associations are an advanced Rails topic, and although they are used in the acts_as_taggable_on_steroids plugin, they're used as plumbing and it's not necessary to fully understand them.

Installation

First, read my article "Guide to Ruby on Rails Migrations". In that article readers learn how to use Rails Migrations to create a database schema for an online social music cataloging application called Discographr. You'll be building on that application for the rest of this article.

Let's try out the acts_as_taggable_on_steroids plugin first. It's not included in the official Rails SVN so you'll need to find it first. Rails comes with a handy script/plugin command that you can use to find the plugin you're looking for:

     
$ script/plugin discover -l | grep viney
http://svn.viney.net.nz/things/rails/plugins/     

The plugin discover script scrapes the wiki page at wiki.rubyonrails.org/rails/pages/Plugins for a list of all known plugin repositories. Now add the repository to your list of known sources:
$ script/plugin source http://svn.viney.net.nz/things/rails/plugins/
This allows you to issue the incredibly simple:
$ script/plugin install acts_as_taggable_on_steroids
You could have just done:
$ script/plugin install \ 
http://svn.viney.net.nz/things/rails/plugins/acts_as_taggable_on_steroids/
But it's a little easier if the repository is known by Rails for other projects. (You can also use a tool called rapt to search for and download plugins. It's available at RubyForge.)

Take a quick look to make sure the plugin was in fact installed in your RAILS_ROOT/vendor/plugin directory.

Next you need to make the changes to the database to support the plugin and allow you to add tags to your models. To do this you'll use Migrations, just as in "The Great Ruby Migration"):

   
$ script/generate migration AddTags
      exists  db/migrate
      create  db/migrate/004_add_tags.rb

Now edit the generated migration file you just created, 004_add_tags.rb, adding this to the self.up method:

     
def self.up
  create_table :tags do |t|
    t.column :name, :string
  end
  
  create_table :taggings do |t|
    t.column :tag_id, :integer
    t.column :taggable_id, :integer
    t.column :taggable_type, :string
    t.column :created_at, :datetime
  end
end       
This migration adds two tables. The first, called tags, will hold the actual tag names. The second associates the tag with a model. The plugin works by using the taggable_type field and using it as the table name (using the standard Rails magic of pluralize and singularize) and looking up the object by the primary key. For your reference, this migration was derived directly from the tests included in the plugin. Tests are one of the things (among several) that the acts_as_taggable_on_steriods plugin added to the DHH version.

Look in RAILS_ROOT/vendor/plugins/acts_as_taggable_on_steroids/test and you'll find all the tests written for the plugin. Tests not only serve as an excellent safety net that allows you to feel much freer to change your code, knowing that you can always run rake test and see what breaks, but they also provide for excellent example usage of a library. It's almost as good as built in documentation! So, you can tell exactly what the plugin requires to function by looking in the schema.rb file under the test directory.

Next, you need to run the migration to actually add the required tables to the schema:

                     
$ rake db:migrate
(in /Users/mattkern/dev/discographr)
== AddTags: migrating =========================================================
-- create_table(:tags, {:force=>true})
   -> 0.7773s
-- create_table(:taggings, {:force=>true})
   -> 1.0804s
== AddTags: migrated (1.8754s) ===============================================                    
That's it, easy as can be. You're ready to start adding tags to your models.

Let's Play Tag

Now it's time to use the added functionality. The first thing you need to do is add an acts_as helper to your models. In Discographr you want all the models to be taggable, so you'll need to add a single line to each of the models. Rails uses acts_as helpers to add functionality or extend the ActiveRecord::Base class and subclasses. So, for example, acts_as_taggable adds tagging functionality to your models in a single call (theoretically), while acts_as_tree adds hierarchical tree functionality to your models. Start off by adding tags to the Artist model.

    
class Artist < ActiveRecord::Base
  acts_as_taggable
end      
That simple declaration adds a ton of functionality to the Artist model. The first thing it does is create a :has_many relationship with the Taggings and Tags models. But "Wait!" you say. You've never defined either of those models! This is one of the features of using plugins. If you look in the plugin directory for your newly installed plugin, you'll notice two model files, tag.rb and tagging.rb. These models are included in your application by virtue of being in the plugins' lib directory. I'm going to issue a warning here, though: Defining models in your plugins can be a handy thing to do, but it can cause problems as well. Doing so makes it possible to clash with the containing application's models.

If you've worked with Rails in the past you know that the :has_many, :has_one, and :has_and_belongs_to_many methods add an awful lot of methods to your models. Since the plugin relies on the :has_many method and polymorphic associations, you get all that functionality by virtue of declaring your model as acts_as_taggable. You'll see those added methods in action later.

So, go ahead and add tags to the other models in Discographr. You want all of the models you've already defined to be taggable so you'll add the acts_as_taggable call to the Album and Song models:

     
class Album < ActiveRecord::Base
  belongs_to :artist
  
  acts_as_taggable

end

class Song < ActiveRecord::Base
  belongs_to :album

  acts_as_taggable

end       

Now that all your models are taggable, you can start using the tag information in your application. As you haven't really written any controllers at this point, you'll use the handy script/console to test-drive your newly taggable models. Fire up the console by issuing:

     
$ script/console  
Start off by creating an artist, album and song:
>>  
                              
a = Artist.new( :name => "Bob Dylan" )
=> #<Artist:0x35589dc @new_record=true, @attributes={"created_on"=>nil, "name"=>"Bob Dylan", "updated_on"=>nil}>
>>  
                              
a.save
=> true
>>  
                              
alb = Album.new( :release_name => "Good As I Been To You",
?>  
                              
:artist => a,
?>  
                              
:year => 1992 )
=> #<Album:0x3500ef8 @new_record=true, @attributes={"created_on"=>nil, "artist_id"=>10001,
"updated_on"=>nil, "year"=>1992, "release_name"=>"Good As I Been To You"}, @artist=#<
Artist:0x35589dc @new_record=false, @new_record_before_save=true, @attributes={"created_on"=>Sun Feb
18 22:46:32 PST 2007, "name"=>"Bob Dylan", "updated_on"=>Sun Feb 18 22:46:32 PST 2007, "id"=>10001},
@errors=#<ActiveRecord::Errors:0x35573fc @base=#<Artist:0x35589dc ...>, @errors={}>>>
>>  
                              
alb.save
=> true
>>  
                              
s = Song.new( :title => "Froggie Went A-Courtin'",
?>  
                              
:length => 386,
?>  
                              
:track_number => 13,
?>  
                              
:album => alb )
=> #<Song:0x34450f4 @new_record=true, @album=#<Album:0x3500ef8 @new_record=false,
@new_record_before_save=true, @attributes={"created_on"=>Sun Feb 18 22:50:47 PST 2007, "artist_id"=
10001, "updated_on"=>Sun Feb 18 22:50:47 PST 2007, "id"=>10000, "year"=>1992, "release_name"=>"Good As
I Been To You"}, @errors=#<ActiveRecord::Errors:0x34f65d4 @base=#<Album:0x3500ef8 ...>,
@errors={}>, @artist=#<Artist:0x35589dc @new_record=false, @new_record_before_save=true,
@attributes={"created_on"=>Sun Feb 18 22:46:32 PST 2007, "name"=>"Bob Dylan", "updated_on"=>Sun Feb 18
22:46:32 PST 2007, "id"=>10001}, @errors=#<ActiveRecord::Errors:0x35573fc @base=#<
Artist:0x35589dc ...>, @errors={}>>>, @attributes={"created_on"=>nil, "track_number"=>13, "title"=
"Froggie Went A-Courtin'", "updated_on"=>nil, "album_id"=>10000, "length"=>386}>
>>  
                              
s.save
=> true  
                            

Now, create a few tags. Remember, the plugin defined the Tag model for you so you can create tags just like any other model you might define:

     
>>  
                              
t1 = Tag.new( :name => "male vocalist" )
=> #<Tag:0x3361700 @new_record=true, @attributes={"name"=>"male vocalist"}>
>>  
                              
t1.save
=> true
>>  
                              
t2 = Tag.new( :name => "children's songs" )
=> #<Tag:0x333a150 @new_record=true, @attributes={"name"=>"children's songs"}>
>>  
                              
t2.save
=> true   
                            
And finally to associate the tags with one of your models, for example a song:
>>  
                              
s.tags << t1 
=> [#<Tag:0x3361700 @new_record=false, @new_record_before_save=true, @attributes={"name"=>"male
vocalist", "id"=>10000}, @errors=#<ActiveRecord::Errors:0x335133c @base=#<Tag:0x3361700 ...>,
@errors={}>>]
>>  
                              
s.tags << t2
=> [#<Tag:0x3361700 @new_record=false, @new_record_before_save=true, @attributes={"name"=>"male
vocalist", "id"=>10000}, @errors=#<ActiveRecord::Errors:0x335133c @base=#<Tag:0x3361700 ...>,
@errors={}>>, #<Tag:0x333a150 @new_record=false, @new_record_before_save=true,
@attributes={"name"=>"children's songs", "id"=>10001}, @errors=#<ActiveRecord::Errors:0x33376e4
@base=#<Tag:0x333a150 ...>, @errors={}>>]
>>  
                              
s.tags.count
=> 2
                            

The << method (remember that in Ruby everything called on an object is a method, << included) was added to your Artist model when you added the acts_as_taggable helper. Recall that it adds an :has_many :tags helper to your model thereby adding the append operator (method!). So, you've just added two tags to your "Bob Dylan" artist object.

>>  
                              
a.tags
=> [#<Tag:0x3361700 @new_record=false, @new_record_before_save=true, @attributes={"name"=>"male
vocalist", "id"=>10000}, @errors=#<ActiveRecord::Errors:0x335133c @base=#<Tag:0x3361700 ...>,
@errors={}>>, #<Tag:0x333a150 @new_record=false, @new_record_before_save=true,
@attributes={"name"=>"children's songs", "id"=>10001}, @errors=#<ActiveRecord::Errors:0x33376e4
@base=#<Tag:0x333a150 ...>, @errors={}>>]
>>  
                              
a.tags.count
=> 2
                            
There's already an awful lot you can do with your application now that you've added the ability to tag your data! Take some time to browse the Rails API documentation and get familiar with all the methods that the association methods add to your models. They'll all work with your tags now, too!

But, it gets better. The acts_as_taggable_on_steroids plugin adds quite a few convenience methods you can use to make development even easier and quicker. The plugin is designed to replicate the functionality provided by the original acts_as_taggable plugin. This means that you can do things like:

>>  
                              
a2 = Artist.new( :name => "The Flaming Lips" )
=> #<Artist:0x326d600 @new_record=true, @attributes={"created_on"=>nil, 
"name"=>"The Flaming Lips", "updated_on"=>nil}>
>> a2.save
=> true
>> a2.tag_list = "alternative, male vocalist"
=> "alternative, male vocalist"
>> a2.save
=> true
>> a2.tags.count
=> 2
                            
Note the two artists objects returned there, Bob Dylan and The Flaming Lips. Add four or five more artists of your choice in the same way and make sure to tag them. Try to use the same tags a few times so that the tag cloud example we'll be working on next will make sense.

Forecast Calls for Clouds

One of the most common approaches to visualizing tag data in most social and folksonomy based applications is the notion of a tag cloud. You've seen these before on sites like Flickr and del.icio.us. A tag cloud is basically a visual representation of the tags present in a system sized according to popularity (in other words, frequency). The acts_as_taggable plugin provides a convenient method for calculating tag frequencies called tag_counts. Unfortunately, the developer of the plugin must have had a MySQL bias because the definition of the tag_counts method includes a find_by_sql call that uses invalid SQL with aggregation functions. Oracle follows the standard and requires that any non-aggregate expressions must be included in the GROUP BY clause. Thus tag_counts breaks even though Oracle is doing the right thing!

There's still hope though; simply add the following to the end of the init.rb file found in the plugin at RAILS_ROOT/vendor/plugins/act_as_taggable_on_steroids:

require File.dirname(__FILE__) + '/lib/acts_as_taggable_override'
Then create a file in RAILS_ROOT/vendor/plugins/acts_as_taggable_on_steroids/lib called acts_as_taggable_override.rb put the following code in it:
module ActiveRecord
  module Acts #:nodoc:
    module Taggable #:nodoc:
      module SingletonMethods
        def tag_counts(options = {})
          logger.debug{"Using overriden tag_counts method"}
          options.assert_valid_keys :start_at, :end_at, :conditions, :at_least, :at_most, :order
          
          start_at = sanitize_sql(['taggings.created_at >= ?', options[:start_at]]) if options[:start_at]
          end_at = sanitize_sql(['taggings.created_at <= ?', options[:end_at]]) if options[:end_at]
          options[:conditions] = sanitize_sql(options[:conditions]) if options[:conditions]
          
          conditions = [options[:conditions], start_at, end_at].compact.join(' and ')
          
          at_least = sanitize_sql(['count(*) >= ?', options[:at_least]]) if options[:at_least]
          at_most = sanitize_sql(['count(*) <= ?', options[:at_most]]) if options[:at_most]
          having = [at_least, at_most].compact.join(' and ')
          
          order = "order by #{options[:order]}" if options[:order]
          limit = sanitize_sql(['limit ?', options[:limit]]) if options[:limit]
          
          Tag.find_by_sql <<-END
            select tags.id, tags.name, count(*) as count
            from tags left outer join taggings on tags.id = taggings.tag_id
                      left outer join #{table_name} on #{table_name}.id = taggings.taggable_id
            where taggings.taggable_type = '#{name}'
              #{"and #{conditions}" unless conditions.blank?}
            group by tags.id, tags.name
            having count(*) > 0 #{"and #{having}" unless having.blank?}
            #{order}
          END
        end
      end
    end
  end
end
That code overrides the existing tag_counts method and fixes several problems: First, it changes the quotes around #{name} to single quotes so that Oracle considers it a literal and avoids an ORA-00904: invalid identifier error. Second, it makes the SQL valid by adding the missing expressions to the GROUP BY clause. It also changes the code around the :start_at and :end_at options and removes the :limit option. Restarting your console or application will ensure the changes are picked up and a calling the method should now return successfully:
>>  
                              
Artist.tag_counts
=> [#<Tag:0x34495b4 @attributes={"name"=>"male vocalist", "id"=>10000,
"count"=>2.0}>, #<Tag:0x3449578 @attributes={"name"=>"children's songs", 
"id"=>10001, "count"=>1.0}>, #<Tag:0x344953c @attributes={"name"=>"alternative", 
"id"=>10002, "count"=>1.0}>]
                            
Hopefully in a future version this bug will be fixed. But until it is, don't forget to reapply these changes if you update to a newer version of the plugin.

The tag_counts method allows you to add conditions like :start_at, :end_at, :at_least, :at_most and :order. These allow you to make queries like:

Artist.tag_counts(:start_at => 7.days.ago) # retrieves tags for added in the last 7 days
Artist.tag_counts(:at_least => 10) # retrieves tags that have been used 10 or more times.
Artist.tag_counts(:order => "name") # order the array of tags by name alphabetically
Now that you have a working tag_counts method you can use it to generate a tag cloud. But before you get started, create the necessary files by using the Rails generator script. Rails includes a generator called scaffold that provides all the needed files for basic CRUD operations on a given model. All the generator requires is that it be passed the name of the model you'll be scaffolding along with the name of the controller to be used. Go ahead and run the scaffold generator for the artist model and catalog controller now:
   
$ script/generate scaffold Artist Catalog       
Now you have the files you need. Fire up the built-in server and see what was created:

           
$ script/server                 
Go to http://localhost:3000/catalog and you'll see the list view that you'll be working with from here on out.

In order to make your tag cloud method available to our entire application you'll put the following code in the RAILS_ROOT/app/helpers/application_helper.rb file. You could put it in the catalog_helper.rb file, but you'll probably want to use the tag_cloud outside the catalog controller, too.

def tag_cloud(tag_counts)
    ceiling = Math.log(tag_counts.max { |a,b| a.count <=> b.count }.count)
    floor = Math.log(tag_counts.min { |a,b| a.count <=> b.count }.count)
    range = ceiling - floor
    
    tag_counts.each do |tag|
      count = tag.count
      size = (((Math.log(count) - floor)/range)*66)+33
      yield tag, size
    end
  end
You probably noticed several calls to Math.log in that listing. This tag cloud method attempts to compensate for the "long tail/power law" phenomenon by using a logarithmic distribution to counter the power curve and balance out the distribution across font sizes. Without doing this you could very easily end up with just a couple large tags and hundreds of small tags. Essentially, the logarithmic distribution magnifies the difference between the high number of low popularity tags.

Next you'll have to add your CSS. As you used the scaffold command to generate a basic view you can add to the scaffold.css file under RAILS_ROOT/public/stylesheets:

.tagCloud {
        margin: 10px;
        font-size: 40px;
}

.tagCloud li {
        display:inline;
}
That style sets the maximum font-size for your tag cloud. If you look back at the method definition for tag_cloud you'll see this: size = (((Math.log(count) - floor)/range)*66)+33. It sets the minimum font-size percentage to 33% and then adds the weighted size to the minimum, resulting in the highest frequency tags being closest to 100% and the lowest frequency tags closest to 33% of the font size you set in the tagCloud CSS class. The nice thing about this algorithm is that it allows for much more variability in the sizing of the tags than do most other tag cloud algorithms. That said, it's best suited for size-based tag clouds, not color-based ones. (I call the latter "heat maps").

Finally, now that the plumbing is in place, you need to add the code to display the tag cloud in a view. Again, since you used the script/generate scaffold command the necessary views and controller actions have been created for you. Let's go ahead and add the tag cloud to the list action and view. First, change Catalog_Controller's list action in RAILS_ROOT/app/controllers/catalog_controller.rb to:

def list
    @artists = Artist.find(:all)
    @artist_tag_count = Artist.tag_counts()
end
You've taken out the pagination that the scaffold added for you just to keep things simple. Also, you added a call to the tag_counts() method so that the view will have access to the tag frequency information. Remember, in Rails views have access to any instance variables in the controller.

So, now that the controller has the data needed to create the tag cloud, finish up with the view. Open up the default view for the list action at RAILS_ROOT/app/views/catalog/list.rhtml. list.rhtml was automatically generated by the scaffold command along with the catalog controller. Add the following to the end of the list.rhtml file (after the last line):

<br />

&ol class="tagCloud">
<% tag_cloud(@artist_tag_count.sort_by {|t| t.name}) do |tag, size| %>
  <li><%= link_to h("#{tag.name}"), { :action => "show_tag/#{tag.name}" }, 
  { :style => "font-size: #{size}%"}%></li>
<% end %>
</ol>
Also, go ahead and remove the pagination links that the scaffold command put in the view. Delete these lines toward the end of the file; otherwise you'll get an exception since @artist_pages doesn't exists in your list action:
<%= link_to 'Previous page', { :page => @artist_pages.current.previous } if @artist_pages.current.previous %>
<%= link_to 'Next page', { :page => @artist_pages.current.next } if @artist_pages.current.next %>

Finally you need to add the show_tag action that is referenced as the action to which your tags link in the cloud. Add this last action to the end of the RAILS_ROOT/app/controllers/catalog_controller.rb file:

def show_tag
    @artists = Artist.find_tagged_with(params[:id])
    @artist_tag_count = Artist.tag_counts()
    render :template => "catalog/list"
end
You don't need to create a view for this action as you'll just use the same view as the list action does. The only difference is that in the link_to call in the view you pass tag.name as a parameter so you can be sure to display only the tag you clicked on. The show_tag action then uses the tag.name parameter with the Artist.find_tagged_with(params[:id]) method call. Simple.

After all that your list.rhtml file should read as follows:

<h1>Listing artists</h1>

<table>
  <tr>
  <% for column in Artist.content_columns %>
    <th><%= column.human_name %></th>
  <% end %>
  </tr>
  
<% for artist in @artists %>
  <tr>
  <% for column in Artist.content_columns %>
    <td><%=h artist.send(column.name) %></td>
  <% end %>
    <td><%= link_to 'Show', :action => 'show', :id => artist %></td>
    <td><%= link_to 'Edit', :action => 'edit', :id => artist %></td>
    <td><%= link_to 'Destroy', { :action => 'destroy', :id => artist }, 
      :confirm => 'Are you sure?', :method => :post %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New artist', :action => 'new' %>

<br />

<ol class="tagCloud">
<% tag_cloud(@artist_tag_count.sort_by {|t| t.name}) do |tag, size| %>
  <li><%= link_to h("#{tag.name}"), { :action => "show_tag/#{tag.name}" }, 
  { :style => "font-size: #{size}%"}%></li>
<% end %>
</ol>
And your catalog_controller.rb should end up:
class CatalogController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @artists = Artist.find(:all)
    @artist_tag_count = Artist.tag_counts()
  end

  def show
    @artist = Artist.find(params[:id])
  end

  def new
    @artist = Artist.new
  end

  def create
    @artist = Artist.new(params[:artist])
    if @artist.save
      flash[:notice] = 'Artist was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @artist = Artist.find(params[:id])
  end

  def update
    @artist = Artist.find(params[:id])
    if @artist.update_attributes(params[:artist])
      flash[:notice] = 'Artist was successfully updated.'
      redirect_to :action => 'show', :id => @artist
    else
      render :action => 'edit'
    end
  end

  def destroy
    Artist.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
  
  def show_tag
    @artists = Artist.find_tagged_with(params[:id])
    @artist_tag_count = Artist.tag_counts()
    render :template => "catalog/list"
  end
end

Now going to http://localhost:3000/catalog/list should display a list of Artists with CRUD functionality along with a tag cloud beneath it:

Figure 1

Clicking on the tags should display a filtered list of artists by tag with the same tag cloud below.

That is but one example of the experience that tags can bring to your application. Tag clouds can convey a great amount of meaning in a very simple format—the mark of a powerful user interface.

Bringing it Home

There are quite a few shortcomings to the acts_as_taggable_on_steroids plugin, as you've seen already. As of this writing, recently the has_many_polymorphs plugin has started to gain acceptance as a more powerful replacement for the acts_as_taggable plugins. As is the case with many solutions that gain flexibility and power, it is a bit more abstract than the plugins we've looked at in this article. As such the plugin is not as much an out-of-the-box, straightforward solution for tagging but it does an excellent job of avoiding many of the inherent challenges of the acts_as_taggable_on_steroids plugin—including potential model definition clashes, incompatibility with Oracle without tweaking, inflexible tag separators, and perhaps most important, the inability to easily query across models for a given tag.

That said, the acts_as_taggable_on_steriods plugin is a very powerful and simple to use extension for any Rails application.


Matt Kern has been searching for and developing ways to make life easier through technologies like Rails for years—mostly an attempt at finding ways to spend ever more time roaming the mountains of Central Oregon with his family. He is the founder of Artisan Technologies Inc. and co-founder of Atlanta PHP.