to associate an image with both a seed employee and seed product
This would require a many-to-many
relationship (either has_and_belongs_to_many
or 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
This would allow you to use:
#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
Because you're using a polymorphic
relationship, you won't be able to use has_and_belongs_to_many
.
The above will set the polymorphism on the join
table; each Picture
being "naked" (without a "creator"). Some hacking would be required to define the original creator of the image.