以前に gem install acts_as_taggable でインストールしたものを試したことがあったんですが、今度はRailsの プラグイン版 を試してみます。 Plugin だとvendor/の下にインストールされるのでほかのアプリにも影響がででないのでできればこちらを使いたいと思います。
インストールscript/plubin install acts_as_taggableDBスキーマの追加
プラグインをインストーしただけではDBにテーブルは作成されません。自分で作成するひつようがあります。 まず migrationを実行します。
script/generate migration add_tag_support生成されたファイルに次のテーブル定義を行います
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 を実行します。
rake migrate
これでacts_as_tabbable プラグインの設定が完了したのでで何か適当なアプリで試してみます
テストアプリの追加まず適当なDBテーブルを用意します。とりあえずBookmark を管理するテーブルを用意してみます。先と同様にmigrationを使ってテーブルを追加します。
class AddBookmark < ActiveRecord::Migration
def self.up
create_table(:bookmarks) do |t|
t.column(:title,:string)
t.column(:url,:string)
end
end
def self.down
drop_table(:bookmarks)
end
end
scaffold を実行してひな形を用意します。
script/generate scaffold bookmarkBookmark モデルでtagが使えるようにします。
class Bookmark < ActiveRecord::Base acts_as_taggable endバグ修正
acts_as_taggable プラグインにはバグがあります。 vendor/plugins//acts_as_taggable/lib/acts_as_taggable.rb の52行目を修正します。 修正前:
tags.collect { |tag| righttag.name.include?(" ") ? "'#{tag.name}'" : tag.name }.join(" ")
修正後:
tags.collect { |tag| tag.name.include?(" ") ? "'#{tag.name}'" : tag.name }.join(" ")
テストの実行vendor/plugins//acts_as_taggable/acts_as_taggable_test.rb にテストを記述します。
require File.dirname(__FILE__) + '/../../../../test/test_helper'
require 'acts_as_taggable'
require 'bookmark'
require 'pp'
class ActsAsTaggableTest < Test::Unit::TestCase
def test_save
bookmark = Bookmark.new();
bookmark.title = "test";
bookmark.url = "http://hogeho.com/"
# TAGを追加する
bookmark.tag_with('tag1 tag2')
bookmark.save
end
def test_tagged_with
test_save
# TAG で絞り込む
b = Bookmark.find_tagged_with('tag1')
assert_equal "test",b[0] .title
b = Bookmark.find_tagged_with('tag2')
assert_equal "test",b[0].title
end
def test_tag_list
test_save
b = Bookmark.find(1)
# 付与されているタグをスペース区切りの一覧で返す
assert_equal 'tag1 tag2' , b.tag_list;
end
end
テストを実行して正常動作を確認。
3 tests, 3 assertions, 0 failures, 0 errors $ ruby acts_as_taggable_test.rb Loaded suite acts_as_taggable_test Started ... Finished in 0.067081 seconds. 3 tests, 3 assertions, 0 failures, 0 errors rake clone_structure_to_testテストが成功しました。 scaffold がはいたrhtmlを適当に修正すればタグを付与したり表示させたりすることができます。


