关联的类型有
- has_one
- has_many
- belongs_to
- has_one :through
- has_many :through
- has_and_belongs_to_many
has_and_belongs_to_many 和has_many :through 的比较可参考
建立两个模型之间多对多的关联关系
7. 多态关联
今天主要想理一下多态关联,多态关联是关联的一种高级形式。
在多态关联中,在同一关联中,一个模型可以属于多个模型。例如,图片模型可以属于雇员模型,也可以属于产品模型。
关联模型定义如下
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
在belongs_to中指定使用多态,可以理解成创建了一个接口,在任何模型中都可以使用
在Employee模型实例上可以使用@employee.pictures
获取图片集合
同样在Product模型实例上可以使用@product.pictures
获取产品的图片集合
在Picture模型实例上可以使用@picture.imageable
获取父对象,不过事先要在声明多态接口的模型中创建外键字段和类型字段
创建图片记录时,可以使用@product.create(XXX)或者@empolyee.create(XXX)会自动填写外键字段和类型字段
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id #主表ID
t.string :imageable_type #主表模型名(Empolyee/Product)
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