mongoid_alize
mongoid_alize copied to clipboard
:alize_to not working when the parent object in a has_many relation is destroyed
To replicate, consider the parent Plant
model which has many child Site
models:
class Plant
field :name, type: String, default: 'something'
has_many :sites, dependent: :nullify
alize_to :sites, :name
end
class Site
belongs_to :plant, index: true
alize_from :plant, :name
end
# in the console -->
p = Plant.create ; s = Site.create plant: p ; p.destroy! ; s.reload
=> <Site _id: 53fe26596731302734010000, plant_id: nil, plant_fields: {"name"=>"something"}>
# in the Site object, the :plant_id becomes nil, but the :plant_fields doesn't
From what I could understand from the code, _denormalize_destroy_to_#{relation}
is defined as an after_destroy
callback. But this method uses [self.#{relation}].flatten.compact
to iterate over all the child objects, which will always return an empty array since the dependent: :nullify
option on the parent will ensure that all child objects have their parent_id fields set to nil.
Changing the callback to a before_destroy
callback fixes the above issue. But that doesn't seem like a good idea (IMO), since it would not work with dependent: :restrict
option.