Ruby on Rails - Tagging with taggable
For Ruby on Rails programmers, there is a cool gem named acts_as_taggable that can be used to quickly and easily implement tagging within your applications.
Installing acts_as_taggable
Open config/environment.rb and put the following line:gem install acts_as_taggable
# output follows
Attempting local installation of 'acts_as_taggable'
Local gem file not found: acts_as_taggable*.gem
Attempting remote installation of 'acts_as_taggable'
Updating Gem source index for: http://gems.rubyforge.org
Successfully installed acts_as_taggable-1.0.4
Installing RDoc documentation for acts_as_taggable-1.0.4...
See taggable on RubyForge.org for more info.require_gem ‘acts_as_taggable‘
Create a table named tags for holding tag names.
- id (primary key)
- name (varchar)
CREATE TABLE `tags` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` ) ,
INDEX ( `name` )
) TYPE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'tags';
Generate an ActiveRecord model class named "Tag"
[frank@srv30 ror]# ruby script/generate model Tag
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/tag.rb
create test/unit/tag_test.rb
create test/fixtures/tags.yml
Open up models/tag.rb and modify your model as follows:
class Tag < ActiveRecord::Base
acts_as_taggable
end
Now, we need to create join tables. According to the RDoc for acts_as_taggable:
If you´re using the simple has_and_belongs_to_many model, you must NOT have a primary key (usually an ‘id’ column) defined on the join table. If you´re using a full join model, you must add a primary key column to the join table. Please see the RDoc documentation on acts_as_taggable macro and the :join_class_name option for the differences between these two approaches.
Since I am interested in creating a join table for resources, I will call my table tags_resources. This table will have two fields
- tag_id
- resource_id
0 Comments:
Post a Comment
<< Home