2012-09-04 83 views
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的嵌套模式表单功能?

回答

1

编辑:哼,我看了你的帖子有点太快了,我以为用where the child references a value in the parent,你的意思是外键parent_id ......我的答案可能仍然有帮助,不确定。

我认为你正在寻找inverse_of选项。尝试:

class Parent < ActiveRecord::Base 
    has_one :child, inverse_of :parent 
end 

class Child < ActiveRecord::Base 
    belongs_to :parent, inverse_of :child 
end 

从DOC:

验证父模型

的存在。如果您想验证一个子记录与父记录相关联,则可以使用validates_presence_of和inverse_of作为该示例说明的:

class Member < ActiveRecord::Base 
    has_many :posts, :inverse_of => :member 
    accepts_nested_attributes_for :posts 
end 

class Post < ActiveRecord::Base 
    belongs_to :member, :inverse_of => :posts 
    validates_presence_of :member 
end 
+1

向这些关联添加inverse_of选项!谢谢罗宾!不知道它为什么有效。认为inverse_of选项的目的是优化双向关联对象的加载。 – TsenYing

+0

很酷,很高兴帮助。 – Robin