Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how to overwrite :destroy method?

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.

like image 831
alex.bour Avatar asked Feb 17 '12 18:02

alex.bour


People also ask

How to delete the record in ror?

Rails delete operation using destroy method By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.

What is the difference between delete and destroy in rails?

Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

What is dependent destroy in rails?

dependent: :destroy Rails, when attempting to destroy an instance of the Parent, will also iteratively go through each child of the parent calling destroy on the child. The benefit of this is that any callbacks and validation on those children are given their day in the sun.


1 Answers

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

like image 191
miked Avatar answered Nov 15 '22 09:11

miked