【问题标题】:Validations Across Models and Nested Model/Object Form in RailsRails 中跨模型和嵌套模型/对象形式的验证
【发布时间】:2012-08-29 14:10:00
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails validation nested-attributes


    【解决方案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
    

    【讨论】:

    • 将 inverse_of 选项添加到关联工作!谢谢罗宾!不知道为什么它有效。认为 inverse_of 选项的目的是优化双向关联对象的加载。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2011-07-05
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多