美文网首页RubyRuby on RailsRuby、Rails知识
Active Record模型间的关联(多态关联)

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

作者: 小新是个程序媛 | 来源:发表于2018-08-06 16:10 被阅读48次

    关联的类型有

    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
    
    模型关联图

    相关文章

      网友评论

      本文标题:Active Record模型间的关联(多态关联)

      本文链接:https://www.haomeiwen.com/subject/ycqgvftx.html