Rails: how to overwrite :destroy method?

alex.bour picture alex.bour · Feb 17, 2012 · Viewed 10.6k times · Source

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.

Answer

miked picture miked · Feb 17, 2012

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).