我有两个模型:
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
from Range
模型这个效果很好。我能够和他的孩子们一起创造新的转变。ActiveRecord
为我做那件事。
问题是:为什么我需要删除该验证才能使其工作?
像这样验证父母存在的事情是timing!!实际上Shift
尚未保存,因此在尝试创建嵌套时ranges
它不会找到父级Shift
在数据库中。
我找到了这个解决方法here http://railsguides.net/2013/07/13/belongs-to-association-and-validate-presence-with-nested-attributes/
class Shift < ActiveRecord::Base
attr_accessible :ranges_attributes
has_many :ranges, :inverse_of => :shift
accepts_nested_attributes_for :ranges, allow_destroy: true
end
我引用同一来源的内容(稍作修改):
使用此选项,rails 不会尝试从数据库获取父级
孩子被验证。父级将从记忆中获取。如果你不这样做
熟悉这个选项我强烈建议你阅读官方的导轨 http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-inverse-of
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)