如何在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
答案 0 :(得分:0)
我相信你要找的是http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html
这将保留相关记录,首先允许存在类型和ID。