Add option to defer persisting additions/removals on collection associations. Add marked_for_deletion
.
#55041
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation / Background
Presently, any additions or removals of existing records to a collection association are persisted to the database immediately, rather than waiting for save to be called manually. This can be unexpected or undesirable in cases such as generating a preview or looking back at what changes just occurred. While there exist some workarounds, they seem a bit cumbersome, and there have occasionally been requests for it to not be persisted immediately, so I thought having a toggle on that behavior might be more convenient.
Detail
:defer
option for collection associations with autosave enabled. Setting this to true will defer the persisting of additions/removals until the parent (or child, in the case of has_many) is saved.concat()
orreplace()
. Usingcollection.destroy(record)
orcollection.delete(record)
still persists immediately, sincemark_for_deletion
/destruction
is simultaneously available.has_many
) or changes in the through record (habtm
,has_many :through
)habtm
orhas_many :through
association now resets the internal through association to keep the records listed on both targets in sync.marked_for_deletion
to Autosave Associations, a mirror ofmarked_for_destruction
that callsdelete
instead ofdestroy
.marked_for_removal?
which checks if either flag is set.<association>_added_records
and<association>_previously_added_records
Additional information
Other previous related discussion:
#17368
#42097
#46685
Rails Forum