How access ActiveRecord::AutosaveAssociation.marked_for_destruction? from within parent model
-
20-09-2019 - |
Question
I have a model, Person, with the following association:
has_many :distributions
accepts_nested_attributes_for :distributions, :allow_destroy => true
validate :distributions_must_total_100
The custom validation currently fails when it shouldn't -- when some of the validations have been marked for destruction -- because they still show up in the attribute "distributions" (in memory, never mind what's in the DB) before the Person and its Distributions are saved.
I would like to use ActiveRecord::AutosaveAssociation.marked_for_destruction?
within my validator, to ignore the distributions that are about to be destroyed.
How do I reach that method? Not quite sure what the relationship of Distribution (your normal Rails model) is to that class.
Is this a horrible unclean hack? It only feels a little dirty, and it's the most precise fix for the problem.
I did step through the ActiveRecord source code in the debugger to confirm that the records actually are marked for destruction (i.e. not a Javascript or form builder bug).
Solution
Turns out you can just call marked_for_destruction?
on an instance of Distribution, and it works fine.