我有两个模型:
class Shift < ActiveRecord::Base
attr_accessible :ranges_attributes
has_many :ranges
accepts_nested_attributes_for :ranges, allow_destroy: true
end
class Range < ActiveRecord::Base
belongs_to :shift
validates :shift, presence: true
end
在我的控制器中,当我想创建一个具有范围的班次时:
Shift.create! params[:shift]
#ActiveRecord::RecordInvalid Exception: Validation failed: Shift ranges shift can't be blank
如果我validates :shift, presence: true
从Range
模型中删除,则效果很好。我可以和他的孩子们进行一次新的轮班。ActiveRecord
为我做到了。
问题是:为什么我需要删除该验证才能进行这项工作?
像这样验证父母在场的事情就是时机!实际上Shift
尚未保存,因此在尝试创建嵌套ranges
时不会Shift
在数据库中找到父级。
我在这里找到了解决方法
class Shift < ActiveRecord::Base
attr_accessible :ranges_attributes
has_many :ranges, :inverse_of => :shift
accepts_nested_attributes_for :ranges, allow_destroy: true
end
并且我引用(略作修改)来自同一来源:
使用此选项,当验证子代时,rails不会尝试从数据库中获取父代。父级将从内存中获取。如果您不熟悉此选项,强烈建议您阅读官方的Rails指南
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句