acts_as_taggable
Posted by tom August 19th, 2006
Acts as taggable is a simple (but powerful) plugin for your ruby on rails applications to make it support tagging. Once you’ve installed it (in my case as a gem – with sudo gem install acts_as_taggable), you’re good to go. What follows is not a tutorial, but more a quick overview what I did to get it to work.
Include acts_as_taggable in your rails environment:require_gem 'acts_as_taggable'
I had to restart the development environment to get this to work.
In my case I had photos which I wanted to be able to tag, so I setup the following database structure:
# table photos
CREATE TABLE `photos` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
PRIMARY KEY (`id`)
);
# table photos_tags
CREATE TABLE `photos_tags` (
`photo_id` int(11) default NULL,
`tag_id` int(11) default NULL
);
# table tags
CREATE TABLE `tags` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
PRIMARY KEY (`id`)
);
Remember that the join table need to have the models in alphabetical order (so actors_tags, tags_users, etc).
Generate a Tag model with ruby script/generate model Tag and put the following in the model you want to tag (in my case photo):
acts_as_taggable
You’ll see that this adds quite a few methods, of which for me the most useful were: tag and find_tagged_with.
Then in your view of the model (probably in new.rhtml – if you keep things standard):
<label for='photo_tag_list'>Tags:</label>
<%= text_field_tag 'tag_list', "" %>
And lastly in your controller:
@photo.tag params[:tag_list]

Leave a Reply