有没有办法在嵌套模型表单的嵌套结构中跨模型进行验证?在我使用的嵌套层次结构中,子模型引用父模型中的属性来执行验证。由于验证是自下而上进行的(首先验证子模型),因此子模型没有对父模型的引用,因此验证失败。例如:
# 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 嵌套模型表单功能的情况下进行这种验证?