Home > Back-end >  How can I tell if a relation was just deleted?
How can I tell if a relation was just deleted?

Time:12-25

Is there something like #saved_changes that will tell me when a relation was destroyed? The destruction happens via accepts_nested_attributes_for.

I have a processing pipeline that my object goes through after being saved, and that pipeline needs to know if a relation was destroyed. Unfortunately, when I call my_obj.images after destroying the image, #image is an empty array.

I haven't found a "images before destruction" method. I suspect that I have to look at the object before committing the change and set a flag on it that something is being destroyed. I'd really like to avoid that if possible.

CodePudding user response:

I have needed this more than once, so I wrote a gem for it:

https://github.com/brandoncc/activerecord-nested_attribute_destruction

Here is a usage example:

class Harbor
  has_many :ships

  accepts_nested_attributes_for :ships, allow_destroy: true
end

harbor.ships_attributes = [harbor.ships.first.attributes.merge('_destroy': true)]
harbor.save!

harbor.ships_destroyed_during_save? # true

See that last line of code? That is what the gem adds :smiley:

  • Related