has_many:通过has_and_belongs_to_many进行多态化

时间:2015-04-27 07:57:43

标签: ruby-on-rails ruby-on-rails-4 activerecord

如何在Rails 4中体现以下想法:

class Package < ActiveRecord::Base
  has_and_belongs_to_many :categories
  has_many :products through :categories
  has_many :insurances, through :categories
end

  class Template < ActiveRecord::Base
  has_and_belongs_to_many :categories
  has_many :products through :categories
  has_many :insurances, through :categories
end

class Category < ActiveRecord::Base
  has_and_belongs_to_many :packages
  has_many :products, as: :productable
  has_many :insurances, as: :productable
end

class Product < ActiveRecord::Base
  belongs_to productable, polymorphic: true
end

产品不仅可以属于包,还可以属于模板。

问题是如何使产品在保存时自动设置正确的productable_type和insurancable_id?

例如

package.categories.first.products.create(name: 'asdasd')

应该有productable_type = 'Package'productable_id: package.id

template.categories.first.products.create(name: 'asdasd')

应该有productable_type = 'Template'productable_id: template.id

1 个答案:

答案 0 :(得分:0)

我相信你要找的是http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

这将保留相关记录,首先允许存在类型和ID。