Ruby on rails Rails中跨模型和嵌套模型/对象表单的验证
是否有一种方法可以在嵌套模型表单的嵌套结构中跨模型进行验证? 在我使用的嵌套层次结构中,子模型引用父模型中的属性来执行验证。 由于验证是自下而上进行的(首先验证子模型), 子项没有对父项的引用,验证失败。 例如:Ruby on rails Rails中跨模型和嵌套模型/对象表单的验证,ruby-on-rails,validation,nested-attributes,Ruby On Rails,Validation,Nested Attributes,是否有一种方法可以在嵌套模型表单的嵌套结构中跨模型进行验证? 在我使用的嵌套层次结构中,子模型引用父模型中的属性来执行验证。 由于验证是自下而上进行的(首先验证子模型), 子项没有对父项的引用,验证失败。 例如: # encoding: utf-8 class Child < ActiveRecord::Base attr_accessible :child_attribute belongs_to :parent validate :to_some_parent_value
# 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
有没有一种方法可以进行这种验证,在这种情况下,子对象引用父对象中的值,并且仍然使用Rails嵌套模型表单功能?编辑:嗯,我读你的帖子有点太快了,我认为在
中,子对象引用父对象中的值时,你指的是外键父对象id
。。。我的回答可能仍然有帮助,不确定
我认为您正在寻找
选项的反向。试试看:
class Parent < ActiveRecord::Base
has_one :child, inverse_of :parent
end
class Child < ActiveRecord::Base
belongs_to :parent, inverse_of :child
end
类父级
从文档:
验证是否存在父模型
如果要验证子记录是否与父记录关联,可以使用validates\u presence\u of和reverse\u of,如本例所示:
类成员:member
接受以下内容的\u嵌套\u属性\u:posts
结束
类Post:posts
验证成员的存在
结束
将“反向”选项添加到关联中会起作用!谢谢你,罗宾!不知道为什么它会起作用。认为option的相反目的是优化双向关联对象的加载。
class Parent < ActiveRecord::Base
has_one :child, inverse_of :parent
end
class Child < ActiveRecord::Base
belongs_to :parent, inverse_of :child
end
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