我有三个对象:
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
我应该如何创建测试种子数据,将图像与种子员工和种子产品相关联?
答案 0 :(得分: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')
代替。
NB。我刚刚注意到:您并未尝试将一个图片与多个所有者关联起来,是吗?因为每张图片只属于一个Imageable
,而 Employee
或Product
。如果你想这样做,你必须建立一个多对多的连接。
答案 1 :(得分:1)
将图片与 种子员工和种子产品
相关联
这需要many-to-many
关系(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
由于您使用polymorphic
关系,因此无法使用has_and_belongs_to_many
。
以上将在join
表上设置多态性;每个Picture
都是“裸体”(没有“创作者”)。需要一些黑客来定义图像的原始创建者。