Rails: how to rewrite: destroy a method?

I tried many things to overwrite the behavior of the method: destroy, but nothing works. At first I used the act_as_paranoia plugin, but it does not work with the model in has_many: through association.

I want to rewrite: 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), and not destroy the record itself.

+6
source share
3 answers

You tried?:

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

EDIT: Based on the comments, there may be something else at work, and it may just be the definition (: dependent => '') in the definition of the association - or if it's HABTM, it may not work at all. Perhaps this information on disposal and destruction through associations will help? Insert the appropriate section below:

Delete or destroy?

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

For has_and_belongs_to_many, deletion and destruction are one and the same: they are so that entries in the connection table are deleted.

For has_many, destroy will always call the destroy method; the record (s) is deleted so callbacks are executed. However, the deletion will either do the deletion in accordance with the strategy specified in: dependent option, or if not: dependent option, then it will follow the default strategy. Default strategy: nullify (set foreign keys to zero), with the exception of has_many: through, where the default strategy is delete_all (delete union entries without starting their callbacks).

+5
source

I think the best way to do this is to rewrite the before_destroy: filter to manage dependents:

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

This does not cancel destroy .

Full callback documentation is here .

+2
source

As Miked said, this code was good if we wanted to destroy varietal β€œmanually”:

 @varietal = Varietal.find('1') @varietal.destroy def destroy update_attribute(:status, 0) end 

It works great. However, as I said, if we update the parent record, I did not find the destroy / delete / delete_all method called by the child ... So, if anyone has an idea ...

0
source

Source: https://habr.com/ru/post/908729/


All Articles