Using acts_as_taggable in Rails (quick reference)

dark posted @ 2007年12月23日 00:28 in 未分类 , 1303 阅读

 

Here are the quickfire steps to use the acts_as_taggable gem...

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=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `tags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `tags_books` (
`tag_id` int(11) NOT NULL DEFAULT '0',
`book_id` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



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

gem install acts_as_taggable

3. Add this line right above the end in your environment.rb

require_gem 'acts_as_taggable'

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

ruby script\generate model Tag

5. In your target object's model.rb file (books.rb in this case) add

acts_as_taggable

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(" ") %>

That's the quick way to get acts_as_taggable working. For more functionality, check this out.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Copyright © 2007

Webdesign, tvorba www stránek

Valid XHTML 1.1