美文网首页我-程序成长-解惑Ruby
ActiveRecord关联关系之多态(polymorphic)

ActiveRecord关联关系之多态(polymorphic)

作者: 就叫初九吧 | 来源:发表于2017-07-21 09:31 被阅读2次

    在多态关联中同一个关联可以属于多个模型

    在belong_to 中指定使用多态,可以理解为创建了一个接口,供别的模型使用。
    在has_one 或者 has_many 通过as参数声明要使用的多态接口

    class Picture < ActiveRecord::Base
      belongs_to :imageable, polymorphic: true
    end
     
    class Employee < ActiveRecord::Base
      has_many :pictures, as: :imageable
    end
     
    class Product < ActiveRecord::Base
      has_many :pictures, as: :imageable
    end
    
    在 belongs_to 中指定使用多态,可以理解成创建了一个接口,可供任何一个模型使用。在 Employee 模型实例上,可以使用 @employee.pictures 获取图片集合。类似地,可使用 @product.pictures 获取产品的图片。
    
    在 Picture 模型的实例上,可以使用 @picture.imageable 获取父对象。不过事先要在声明多态接口的模型中创建外键字段和类型字段:
    
    class CreatePictures < ActiveRecord::Migration
      def change
        create_table :pictures do |t|
          t.string  :name
          t.integer :imageable_id
          t.string  :imageable_type
          t.timestamps
        end
      end
    end
    上面的迁移可以使用 t.references 简化:
    
    class CreatePictures < ActiveRecord::Migration
      def change
        create_table :pictures do |t|
          t.string :name
          t.references :imageable, polymorphic: true
          t.timestamps
        end
      end
    end
    

    相关文章

      网友评论

        本文标题:ActiveRecord关联关系之多态(polymorphic)

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