使用accepts_nested_attributes_for时忽略验证失败(即防止回滚)?

发布于 2024-09-27 17:05:14 字数 551 浏览 0 评论 0原文

因此,假设我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫腻 2024-10-04 17:05:15

您可以在没有“accepts_nested_attributes_for :children”的情况下解决它,并将单个对象单独保存在控制器中......

You could solve it without "accepts_nested_attributes_for :children" and save the single objects in your controller seperately...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文