は、ポリモーフィック関連は
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
ポリモーフィック団体
団体にもう少し高度なねじれがポリモーフィックな関連です。ポリモーフィックな関連付けでは、モデルは複数の他のモデルに1つの関連で属している可能性があります。たとえば、従業員モデルまたは製品モデルのいずれかに属する画像モデルがあるとします。
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
あなたは、他のモデルが使用できるインターフェイスを設定すると多型belongs_toの宣言と考えることができます。従業員モデルのインスタンスから、画像のコレクションを取得することができます。@ employee.pictures。
同様に、@ product.picturesを取得できます。
あなたは絵のモデルのインスタンスを持っている場合は、picture.imageable @を経由してその親に取得することができます。この作業を行うには、外部キー列と多型インターフェイスを宣言するモデルのtype列の両方を宣言する必要があります:
class CreatePictures < ActiveRecord::Migration
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
end
end
この移行はt.referencesフォームを使用して単純化することができます。
class CreatePictures < ActiveRecord::Migration
def change
create_table :pictures do |t|
t.string :name
t.references :imageable, :polymorphic => true
t.timestamps
end
end
end