我有两个模型:
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
当我想在我的 Controller 中创建一个具有我得到的范围的类次时:
Shift.create! params[:shift]
#ActiveRecord::RecordInvalid Exception: Validation failed: Shift ranges shift can't be blank
如果我从 Range
模型中删除 validates :shift, Presence: true
,效果会非常好。我能够和他的 children 一起创造新的转变。 ActiveRecord
为我做到了这一点。
问题是:为什么我需要删除该验证才能使其正常工作?
最佳答案
像这样验证 parent 在场的事情是时机!!实际上,Shift
尚未保存,因此在尝试创建嵌套范围
时,它不会在数据库中找到父级Shift
。
我找到了这个解决方法 here
class Shift < ActiveRecord::Base
attr_accessible :ranges_attributes
has_many :ranges, :inverse_of => :shift
accepts_nested_attributes_for :ranges, allow_destroy: true
end
我引用同一来源(稍作修改):
With this option rails won't try to get parent from database when child is validated. The parent will be got from memory. If you don't familiar with this option I strongly recommend you to read an official rails guide
关于ruby-on-rails - 嵌套属性无法使用新父级创建子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991443/