Update nested attributes objects independently from parent model

298 views Asked by At

I have a parent model 'page' and nested attributes model 'page_modules' which at same time are modeled by 'Single Table Inheritance' pattern.

My problem is when I try to save different generated 'page_modules', if one of these is not validated, the whole model and nested attributes are not updated, even if some of these nested attributes pass the validation. ¿Is there a way to update all the validated 'page_modules' and only refuse not validated 'page_modules'?

1

There are 1 answers

3
max On

If I have understood you correctly you want to silently drop the nested attributes if they are invalid and continue anyways. You can do this with the reject_if: option:

class Page < ApplicationRecord
  has_many :page_modules
  accepts_nested_attributes_for :page_modules, reject_if: :page_module_invalid?

  private
  
  def page_module_invalid?(attributes)
    !page_modules.new(attributes).valid?
  end   
end