Friday, February 01, 2008

Using acts_as_taggable in Rails

change some step from <a href="http://noobonrails.blogspot.com/2005/11/using-actsastaggable-in-rails-quick.html">article</a>: http://noobonrails.blogspot.com/2005/11/using-actsastaggable-in-rails-quick.html
1. In your project database, add two tables, tags and tags_[model you're linking to], here's an example sql script:
CREATE TABLE `books` (
`id` int(6) unsigned NOT NULL auto_increment,
`title` varchar(50) NOT NULL default '',
`author` varchar(50) NOT NULL default '',
`description` text NOT NULL,
`created_on` datetime NOT NULL default '0000-00-00 00:00:00',
`updated_on` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `tags` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `tags_books` (
`tag_id` int(11) NOT NULL default '0',
`book_id` int(11) NOT NULL default '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

2. at a command prompt, from in your project directory, run
gem install acts_as_taggable

3. Create a tag model. You can do this manually or with the generator like so:

ruby script\generate model tag
ruby script\generate scaffold book

5. copy gems/acts_as_taggable/lib/taggable.rb to rails_app/lib and add
require 'taggable'
The new version 2.0 now uses the Rails standard join table names. In the past it was always prefixed by tags,
independent of the alphabetical order.
If you would like to upgrade without changing your table names, or if you prefer the other style - modify
your models as follows:
require 'taggable'
class Photo < ActiveRecord::Base
acts_as_taggable
end

becomes:
require 'taggable'
class Photo < ActiveRecord::Base
acts_as_taggable :join_table => "tags_photos"
end

6. In your target object's controller (books_controller.rb for us) add this line under your
if @books.save line..
@book.tag(params[:tags])

7. Add this to your _forms partial
tags for this book: <%= text_field_tag('tags', '') %>

8. To get the items to show in yor list.rhtml view, you can call them with this
<%= book.tag_names.join(" ") %>

9. Has a native tag cloud supports. Get more infomation from Docs.
That's the quick way to get acts_as_taggable working.

No comments :