Rails: how to overwrite :destroy method?

不问归期 提交于 2019-12-23 09:04:51

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/9333159/rails-how-to-overwrite-destroy-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!