Question

I tried lot of things to overwrite the behavior of the :destroy method but nothing works. I used first the acts_as_paranoia plugin, but it doesn't work with a model in a has_many :through association.

I want to overwrite :destroy method just to do something like this:

  def destroy
    _run_destroy_callbacks { delete }
  end

  def delete    
    self.update_attribute(:status => 0)
    freeze
  end

That is, I just want to update another field (status to 0) instead of destroying the record itself.

Was it helpful?

Solution

Have you tried?:

 class MyClass < ActiveRecord::Base
  def destroy
    update_attribute(:status, 0)
  end
 end

EDIT: Based on comments, there might be something else at work and it might just be the (:dependent=>'') designation on the association definition -- or if it's a HABTM, it might not work at all. Maybe this info on delete and destroy through associations will help? Pasted relevant section below:

Delete or destroy?

has_many and has_and_belongs_to_many associations have the methods destroy, delete, destroy_all and delete_all.

For has_and_belongs_to_many, delete and destroy are the same: they cause the records in the join table to be removed.

For has_many, destroy will always call the destroy method of the record(s) being removed so that callbacks are run. However delete will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is :nullify (set the foreign keys to nil), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

OTHER TIPS

I think that the best way to do this is to overwrite the before_destroy: filter to manipulate the dependents:

def Model
    before_destroy: mark_as_deleted

    def mark_as_deleted  
        self.update_attribute(:status => 0)
    end
end

This wouldn't cancel the destroy though.

The full callback documentation is here.

As Miked said, this code was the good if we want to destroy the varietal "manually":

@varietal = Varietal.find('1')    
@varietal.destroy 

def destroy
  update_attribute(:status, 0)
end

This works perfectly. However, as I said, if we update the parent record, I didn't find the destroy/delete/delete_all method called on the child... So if someone has an idea...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top