【问题标题】:Ignore validation failure when using accepts_nested_attributes_for (i.e. prevent rollback)?使用 accept_nested_attributes_for 时忽略验证失败(即防止回滚)?
【发布时间】:2010-10-19 07:10:17
【问题描述】:

假设我有 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 个孩子未能通过验证。我只是想保存有效记录...

非常感谢帮助,谢谢!

附:使用:reject_if 如果不是我的选项,因为我需要能够访问无效记录,直到我将其保存到数据库中(此时我想拒绝仍然无效的记录)

【问题讨论】:

    标签: ruby-on-rails validation nested-forms rollback nested-attributes


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 2011-07-26
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 2014-01-20
      相关资源
      最近更新 更多