如果子对象验证失败,ActiveRecord 仍会保存父对象
对于这样的关系设置:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
validates_presence_of :first_name
end
p = Parent.new
p.children.build
p.save
=> false
p.errors
=> {:children => ["is invalid"]}
是否有一种方法可以保留子对象的验证,但不让其失败的验证阻止父对象的保存?
With a relationship setup like:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
validates_presence_of :first_name
end
p = Parent.new
p.children.build
p.save
=> false
p.errors
=> {:children => ["is invalid"]}
Is there a way to keep the validations on the child object, but not have their failed validation block the save of the parent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看
ActiveRecord::Validations
中的save(options={})
。可以传入
:validate =>; false
为 save(),这将跳过对valid?
的调用。这也将跳过父对象上的任何验证,因此如果父对象也有验证,您可能需要做一些更多的事情。
来源
Take a look at
save(options={})
inActiveRecord::Validations
.You can pass in
:validate => false
to save(), which will skip the call tovalid?
.This will also skip any validations on the parent object, so you may have to do something more involved if the parent has validations as well.
Source
这不是 Rails 风格,但它回答了你的问题。所以自己管理关联即可:
It's not rails style, but it answers your question. So just manage association by yourself: