我有三个对象:
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
我应该如何创建测试种子数据,将图像与种子员工和种子产品相关联?
最佳答案
to associate an image with both a seed employee and seed product
这需要一个多对多
关系(has_and_belongs_to_many
或has_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
因为您正在使用多态
关系,所以您将无法使用has_and_belongs_to_many
。
上面将在join
表上设置多态性;每张 Picture
都是“裸”的(没有“创作者”)。需要一些黑客来定义图像的原始创建者。
关于ruby-on-rails - 如何创建多态关系的种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329769/