根据父模型验证模型
我有两个模型,一个是另一个的父模型,父模型accept_nested_attributes_for 和validates_linked 子模型。
但是,我的一些验证有一个 :if ,需要检查父级的属性之一。
我在想我可以做这样的事情:
validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?}
但是,在验证时似乎没有设置“父”关系(我假设孩子首先被实例化和验证。
因此有什么方法可以做我在想可以吗?
I have two models, one is the parent of the other, and the parent accepts_nested_attributes_for and validates_associated the children.
However, some of my validations have an :if that needs to check one of the properties of the parent.
I was thinking that I could do something like this:
validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?}
However, the 'parent' relationship doesn't appear to be setup at the time of validation (I would assume the children get instantiated and validated first.
Therefore is there any way of doing what I'm thinking of? Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以根据需要使用 before_update 或 before_create 回调,如下所示。
You can use before_update or before_create callbacks as per your need like this..
这种验证应该有效:
但它不会
据我了解,原因是,因为使用acceptes_nested_attributes_for 是通过一个事务直接创建嵌套对象到数据库,而不通过任何子验证。
您可以在这里做什么:在父模型中编写自己的验证并验证创建子对象。
This kind of validation should work:
But it won't
The reason is, as far as I understand, beause using
acceptes_nested_attributes_for
is creating nested objects straight to database via one transaction without passing any children validations.What you can do here: write your own validation in parent model and validate creating children objects.
使用
:inverse_of
选项进行父级关联,因此子级在构建时将拥有对父级的引用。Use the
:inverse_of
option for the association on the parent, so the children will have a reference to the parent when they are built.