I have a case where a model Parent has many children. The model Child has some validations.
In the Parent model form, I'm building multiple instances of the model Child using nested attributes. The problem is that if one of the children's validations fail, the whole Parent model doesn't save and all the other valid children don't get created.
Is there a way to prevent this behavior and create all the valid associations and silently fail the invalid ones ?
I tried to remove the inverse_of option, but it didn't work.
UPDATE:
It seems that It's not possible, so I came out with this solution. I added the skip_validation to avoid validating the associated records twice (One in the children_attributes= method and the other when saving).
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