首页 > 解决方案 > 如果嵌套关联验证失败,如何允许记录保存事件

问题描述

我有一个模型父母有很多孩子的案例。模型 Child 有一些验证。

在 Parent 模型表单中,我正在使用嵌套属性构建模型 Child 的多个实例。问题是,如果其中一个孩子的验证失败,则整个 Parent 模型不会保存,并且不会创建所有其他有效的孩子。

有没有办法防止这种行为并创建所有有效的关联并默默地失败无效的关联?

我试图删除 inverse_of 选项,但它没有用。

更新

看来这是不可能的,所以我想出了这个解决方案。我添加了 skip_validation 以避免两次验证关联的记录(一个在 children_attributes= 方法中,另一个在保存时)。

class Parent
  children_attributes=(attributes)
    super

    new_children = self.children.select { |child| child.new_record? }

    new_children.each do |child|
      if child.valid?
        child.skip_validation = true
      else
        self.children.delete(child)
      end
    end 
  end
end

class Child
  attr_accessor :skip_validation    

  validates :attribute, presence: true, unless: :skip_validation?

  def skip_validation?
    !!skip_validation
  end
end

标签: ruby-on-railsaccepts-nested-attributes

解决方案


推荐阅读