【问题标题】:How to create seeds of a polymorphic relationship如何创建多态关系的种子
【发布时间】:2016-05-21 15:57:10
【问题描述】:

我有三个对象:

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

我应该如何创建测试种子数据,以将图像与种子员工和种子产品相关联?

【问题讨论】:

    标签: ruby-on-rails ruby polymorphism


    【解决方案1】:

    将图像与种子员工和种子产品相关联

    这需要many-to-many 关系(has_and_belongs_to_manyhas_many :through):

    #app/models/product.rb
    class Product < ActiveRecord::Base
      has_many :images, as: :imageable
      has_many :pictures, through: :images
    end
    
    #app/models/employee.rb
    class Employee < ActiveRecord::Base
      has_many :images, as: :imageable
      has_many :pictures, through: :images
    end
    
    #app/models/image.rb
    class Image < ActiveRecord::Base
      belongs_to :imageable, polymorphic: true
      belongs_to :picture
    end
    
    #app/models/picture.rb
    class Picture < ActiveRecord::Base
      has_many :images
    end
    

    这将允许您使用:

    #db/seed.rb
    @employee = Employee.find_or_create_by x: "y"
    @picture  = @employee.pictures.find_or_create_by file: x
    
    @product = Product.find_or_create_by x: "y"
    @product.pictures << @picture
    

    ActiveRecord, has_many :through, and Polymorphic Associations


    因为您使用的是polymorphic 关系,所以您将无法使用has_and_belongs_to_many

    上面将设置join表上的多态性;每个Picture 都是“裸体的”(没有“创造者”)。需要进行一些黑客攻击才能定义图像的原始创建者。

    【讨论】:

      【解决方案2】:

      改为从has_many 结尾创建它们:

      employee = Employee.create! fields: 'values'
      employee.pictures.create! fields: 'values'
      
      product = Product.create! fields: 'values'
      product.pictures.create! fields: 'values'
      

      虽然只是一个简短的说明:播种时,您可能已经在数据库中拥有所需的数据,所以我会改用instance = Model.where(find_by: 'values').first_or_create(create_with: 'values')

      注意。我刚刚注意到:您不会尝试将 一个 图像与 多个 所有者相关联,是吗?因为每张图片只属于一个Imageable,即或者一个Employee或一个Product。如果你想这样做,你必须设置一个多对多连接。

      【讨论】:

      • 对。 Employees 和Products 需要很多图片吗? (如果是,则忽略此评论,但是)如果不是,您可以反转连接 - 将外键放在这些表上的 picture - 然后您可以在 Picture 一侧只有两个 has_manys,不需要它们是多态的。
      猜你喜欢
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 2012-03-16
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2013-06-27
      相关资源
      最近更新 更多