A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belongs to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared.
polymorphic association 是一個(gè)比較亮瞎眼的高級(jí)關(guān)聯(lián)患亿,用這種關(guān)聯(lián)扎瓶,可以讓一個(gè)model被兩個(gè)或兩個(gè)以上的model擁有,一個(gè)簡單的單一關(guān)聯(lián)刽沾,例如缀蹄,你有一張pic model峭跳,同時(shí)屬于employee和product,可以這樣聲明:
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
你可以把一個(gè)polymorphic的屬于關(guān)系聲明當(dāng)作一個(gè)其他mode可以使用的接口缺前。
比如你實(shí)例化了一個(gè)Employee model蛀醉,你可以取回一個(gè)圖像的collection:@employee.pictures
同樣地,你也可以取回@product.pictures
如果你有一個(gè)實(shí)例化了一個(gè)圖片的model衅码,你可以通過@picture.imageable拯刁,為了讓這些工作有效,你需要聲明一個(gè)外鍵逝段,和一個(gè)字段類型垛玻。
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
add_index :pictures, [:imageable_type, :imageable_id]
end
end
你也可以使用t.references的形式
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.references :imageable, polymorphic: true, index: true
t.timestamps
end
end
end
下面這樣圖片可以讓你清晰的看清楚這三張model之間的關(guān)系以及polymorphic的用法
來源:Rails Guides
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations