2
有没有一种方法可以在嵌套模型表单的嵌套结构内跨模型进行验证? 在我正在使用的嵌套层次结构中,子模型引用父级中的属性来执行验证。 由于验证是自下而上完成的(首先验证子模型), 孩子没有对父级的引用并且验证失败。 例如:在Rails中跨模型和嵌套模型/对象表单进行的验证
# encoding: utf-8
class Child < ActiveRecord::Base
attr_accessible :child_attribute
belongs_to :parent
validate :to_some_parent_value
def to_some_parent_value
if child_attribute > parent.parent_attribute # raises NoMethodError here on ‘parent’
errors[:child_attribute] << "Validation error."
end
end
end
class Parent < ActiveRecord::Base
attr_accessible :parent_attribute
has_one :child
accepts_nested_attributes_for :child
end
在控制台:
> p=Parent.new({ "parent_attribute" => "1", "child_attributes" => { "child_attribute" => "2" }})
> p.valid?
=> NoMethodError: undefined method `parent_attribute' for nil:NilClass
有没有办法有这种验证那里的孩子在家长参考值,并仍然使用Rails的嵌套模式表单功能?
向这些关联添加inverse_of选项!谢谢罗宾!不知道它为什么有效。认为inverse_of选项的目的是优化双向关联对象的加载。 – TsenYing
很酷,很高兴帮助。 – Robin