--- layout: old_post title: Rails/プラグイン/acts_as_taggableを試してみる。 permalink: /tatsuya/show/194-rails-acts-as-taggable ---
ブログを整理するのにカテゴリかタグで分類してみようと思い立ったので、楽にプラグインを使ってみるacts_as_taggableが良い感じらしい。
script/plugin install acts_as_taggable
でタグ用のテーブルを作る、↑のサイトの通りで良い?
script/generate migration add_tag_support
でできたmigrateファイルに以下をコピー
class AddTagSupport < ActiveRecord::Migration def self.up create_table :tags do |t| t.column :name, :string end create_table :taggings do |t| t.column :tag_id, :integer t.column :taggable_id, :integer t.column :taggable_type, :string end add_index :tags, :name add_index :taggings, [:tag_id, :taggable_id, :taggable_type] end def self.down drop_table :tags drop_table :taggings end end
migrate実行でテーブル作る
rake migrate
でこんな感じでチョコチョコ改造、deliciousのブックマークを取り込む⇒タグ付けしてみる。
class Post < ActiveRecord::Base acts_as_taggable end doc = REXML::Document.new (https://del.icio.us/v1/posts/get戻り値) doc.elements['posts'].each{|pos| newPost = Post.new newPost.title = pos.attributes['description'].to_s newPost.body = pos.attributes["extended"].to_s newPost.body += "<a href='#{pos.attributes['href'].to_s}'>[Link]</a>" newPost.tag_with(pos.attributes["tag"]) newPost.save end end }
こんな感じ、適当に動かしてDB見ると上手く入ってるみたいなので使ってみる
posts = Post.find_tagged_with('hoge')
シンプルで良いね~、さぁちゃんと動くか