使用accepts_nested_attributes_for时忽略验证失败(即防止回滚)?
因此,假设我有 Person 和 Child 模型:
class Person < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
end
class Child < ActiveRecord::Base
belongs_to :parent, :class_name => "Person"
validates_presence_of :name
end
现在,当我使用嵌套表单并保存具有 2 个新子项的 Person 时,如果其中一个子项无法验证(即它将回滚),则整个事务将失败。
如何忽略此验证失败并仅保存有效的 1 个人和 1 个孩子?我不希望整个交易失败,因为 1 个孩子未通过验证。我只是想保存有效记录...
非常感谢您的帮助,谢谢!
PS 使用 :reject_if
如果不是我的选择,因为我需要能够访问无效记录,直到将其保存到数据库中(此时我想拒绝剩余的记录)无效的)
So suppose I have the Person and Child models:
class Person < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
end
class Child < ActiveRecord::Base
belongs_to :parent, :class_name => "Person"
validates_presence_of :name
end
Now when I use a nested form and save a Person with 2 new children, the entire transaction will fail if one of the children fails to validate (i.e. it will rollback).
How do I ignore this validation failure and just save the 1 Person and 1 child that are valid? I do not want the entire transaction to fail because 1 child failed the validation. I simply want to save the valid records...
Help much appreciated, thanks!
P.S. using :reject_if
if not an option for me because I need to be able to access the invalid records up until the moment I save it into the database (at which time I want to reject the ones that remain invalid)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在没有“accepts_nested_attributes_for :children”的情况下解决它,并将单个对象单独保存在控制器中......
You could solve it without "accepts_nested_attributes_for :children" and save the single objects in your controller seperately...