ruby-on-rails - 如何创建多态关系的种子

标签 ruby-on-rails ruby polymorphism

我有三个对象:

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_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


因为您正在使用多态 关系,所以您将无法使用has_and_belongs_to_many

上面将在join 表上设置多态性;每张 Picture 都是“裸”的(没有“创作者”)。需要一些黑客来定义图像的原始创建者。

关于ruby-on-rails - 如何创建多态关系的种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329769/

相关文章:

ruby-on-rails - ActiveRecord::StatementInvalid、PG::UndefinedTable 错误,但生成的 SQL 有效

javascript - Ember 创建多态记录

ruby - 如何在 ruby​​ 模块之间共享方法

ruby - 如何从ansible脚本调用capistrano

C++ 避免重新定义需要返回多态类型的代码

C++接口(interface)设计问题

ruby-on-rails - 无法在 Snow Leopard 上安装乘客 3(使用 RVM 和 ruby​​ 1.9.2)

ruby-on-rails - 添加 rails link_to、mail_to 后,haml 删除点之前的空格

ruby-on-rails - 如何在Rails 4中使用Lucene/Solr?

haskell - Either a 和 Either Int 有什么区别?什么是要么 a ?多态类型构造函数?它的目的是什么?