2

有没有办法在嵌套模型表单的嵌套结构中跨模型进行验证?在我使用的嵌套层次结构中,子模型引用父模型中的属性来执行验证。由于验证是自下而上进行的(首先验证子模型),因此子模型没有对父模型的引用,因此验证失败。例如:

# 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 嵌套模型表单功能的情况下进行这种验证?

4

1 回答 1

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

从文档:

验证父模型的存在

如果要验证子记录是否与父记录相关联,可以使用 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
于 2012-09-04T21:42:49.577 回答