Skip to content

Instantly share code, notes, and snippets.

@pinzolo
Last active August 29, 2015 14:04
Show Gist options
  • Save pinzolo/14c026094b535a88c4a5 to your computer and use it in GitHub Desktop.
Save pinzolo/14c026094b535a88c4a5 to your computer and use it in GitHub Desktop.
polymorphic を利用した has_many な関連を付与する
# xxx_create_tags.rb
class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :name, null: false
end
add_index :tags, :name, unique: true
end
end
# xxx_create_taggings.rb
class CreateTaggings < ActiveRecord::Migration
def change
create_table :taggings do |t|
t.references :taggable, polymorphic: true, null: false
t.integer :tag_id, null: false
end
add_index :taggings, :tag_id
add_index :taggings, [:taggable_type, :taggable_id, :tag_id], unique: true, name: 'taggings_uk'
end
end
# tag.rb
class Tag < ActiveRecord::Base
unloadable
has_many :taggings, dependent: :destroy
end
# tagging.rb
class Tagging < ActiveRecord::Base
unloadable
belongs_to :tag
belongs_to :taggable, polymorphic: true
end
# taggable.rb
module Taggable
extend ActiveSupport::Concern
included do
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
end
def add_tag(name)
return if tags.where(name: name).exists?
tag = Tag.where(name: name).first || Tag.new(name: name)
tags << tag
end
def remove_tag(name)
tag = Tag.where(name: name).first
tags.delete(tag) if tag && tags.include?(tag)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment