栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Ruby开发

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

Ruby开发 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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: trueend
 class Employee < ApplicationRecord
  has_many :pictures, as: :imageableend
 class Product < ApplicationRecord
  has_many :pictures, as: :imageableend

在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]  endend

也可以使用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
  endend

模型关联图



作者:小新是个程序媛
链接:https://www.jianshu.com/p/1608552cad9a

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/226331.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号