什么是Polymorphic Associations
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 是一个比较亮瞎眼的高级关联,用这种关联,可以让一个model被两个或两个以上的model拥有,一个简单的单一关联,例如,你有一张pic model,同时属于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
你可以把一个polymorphic的属于关系声明当作一个其他mode可以使用的接口。
比如你实例化了一个Employee model,你可以取回一个图像的collection:@employee.pictures
同样地,你也可以取回@product.pictures
如果你有一个实例化了一个图片的model,你可以通过@picture.imageable,为了让这些工作有效,你需要声明一个外键,和一个字段类型。
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之间的关系以及polymorphic的用法
image.png来源:Rails Guides
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations