Active Record模型间的关联(多态关联)

关联的类型有

  1. has_one
  2. has_many
  3. belongs_to
  4. has_one :through
  5. has_many :through
  6. 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
模型关联图
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,150评论 0 10
  • 在开发中常常会涉及到多个模型进行关联的操作.Rails支持六种关联: 为了后续的内容分析,事先创建以下模型 bel...
    李傲娢阅读 3,909评论 1 1
  • 执子之手, 与子偕老。 生命的分分秒秒。 爱的誓言, 已化作 古老的年轮, 盘根错节, 深深镌刻在泥土中。 看不到...
    人间印象阅读 1,436评论 0 0
  • (1) 如果说这个世界上有一样东西最让人害怕,那应该是非“时间”莫属了。 年初你还在朋友圈洋洋得意的炫耀着新的一年...
    北城浪子阅读 3,081评论 1 15
  • 本文主要讲述golang的gui库andlabs/ui使用。目前该库还不是很完善。 环境说明: 系统:Win10 ...
    小墨马阅读 12,588评论 4 52