Rails - why `accepts_nested_attributes_for` sets` autosave` to true

In Ruby on Rails, if you declare accepts_nested_attributes_for in your model, it is set to true for the child association. It's necessary?

In my opinion, Rails will already check all new and changed children without declaring autosave: true . Apparently, this will cover all cases when you accept nested attributes for a child association. However, with autosave: true child is now checked every time the parent is saved , even if it does not change .

This can have serious unforeseen consequences, especially if, for example, you modify the child model in such a way that a large volume of your records is invalid.

+4
source share
2 answers

Try setting validate: false in the association. You can see from http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html that activating autosave (via accepts_nested_attributes_for in our case) always checks the record if you do not use validate: false

+1
source

Good question! I just stumbled upon this surprise.

I think Rails will save or check new child entries when autosave is nil (by default).

In save_belongs_to_association(reflection) , it looks like it only saves the related record if it is a new record or autosave enabled .

  saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) 

I always found that the autosave option is a bit confusing / inconsistent ... But now we are probably stuck with it for reasons of backward compatibility ...

0
source

Source: https://habr.com/ru/post/1501331/


All Articles