我试图弄清楚为什么我的创建无法正常工作。如果我在下面有以下两个模型
class Product < ActiveRecord::Base
belongs_to :product_template
has_many :presentations, through: :product_presentations
has_many :product_presentations
accepts_nested_attributes_for :product_presentations
validates :start_date, :product_template_id, presence: true
validates :start_date, uniqueness: true
end
class ProductPresentation < ActiveRecord::Base
belongs_to :product
belongs_to :course
belongs_to :presentation
validates_presence_of :product_id, :course_id, :presentation_id
validates_uniqueness_of :presentation_id, :scope => :product_id
end
然后在控制台中输入以下内容。
product = Product.new(
{"start_date"=>"Sat, 06 Sep 2014 00:00:00 +0200",
"product_template_id"=>"5", "product_presentations_attributes"=>{
"0"=>{"course_id"=>"1", "presentation_id"=>"1"},
"1"=>{"course_id"=>"2", "presentation_id"=>"2"}}})
它应该保存,但出现以下错误
#<ActiveModel::Errors:0x007f9eaeb9d698 @base=#<Product id: nil, product_template_id: 5, start_date: "2014-09-05 22:00:00", created_at: nil, updated_at: nil>, @messages={:"product_presentations.product_id"=>["can't be blank"]}>
现在,我了解到product_presentations_attributes哈希中没有product_id,但是我认为这是自动迁移的,因为它是通过产品创建的。
我已经完成了这项工作,但现在我不知道该如何弄乱它。任何帮助表示赞赏。
酷...在发布此内容后,阅读了我自己的文章,我试图删除对product_id存在的验证。
这似乎可以修复错误。
我猜想这是accepts_nested_attributes_for
in rails的限制-父对象无法在模型中验证它的外键。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句