elanbeat's wiki
ActsAsTaggableHowTo

Acts As Taggable

事前準備

インストール


$ ruby script/plugin install acts_as_taggable
+ ./acts_as_taggable/init.rb
+ ./acts_as_taggable/lib/README
+ ./acts_as_taggable/lib/acts_as_taggable.rb
+ ./acts_as_taggable/lib/tag.rb
+ ./acts_as_taggable/lib/tagging.rb
+ ./acts_as_taggable/test/acts_as_taggable_test.rb

データベース設定


$ ruby script/generate migration add_tag_support
      exists  db/migrate
      create  db/migrate/002_add_tag_support.rb
$ vi db/migrate/002_add_tag_support.rb
$ cat db/migrate/002_add_tag_support.rb
class AddTagSupport < ActiveRecord::Migration
  def self.up
    #Table for your Tags
    create_table :tags do |t|
      t.column :name, :string
    end

    create_table :taggings do |t|
      t.column :tag_id, :integer
      #id of tagged object
      t.column :taggable_id, :integer
      #type of object tagged
      t.column :taggable_type, :string
    end
  end

  def self.down
    drop_table :tags
    drop_table :taggings
  end
end
$ rake migrate -t -v
(in /dir)
** Invoke migrate (first_time)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
-- AddTagSupport: migrating 
---------------------------------------------------
-- create_table(:tags)
   -> 0.0400s
-- create_table(:taggings)
   -> 0.0125s
-- AddTagSupport: migrated (0.0527s) 
------------------------------------------

** Invoke db:schema:dump (first_time)
** Invoke environment
** Execute db:schema:dump
** Execute migrate

使用例

モデルでacts_as_taggableを指定する。


class Content < ActiveRecord::Base
  acts_as_taggable
end

参考