gpt4 book ai didi

ruby-on-rails - rails : how to overwrite :destroy method?

转载 作者:行者123 更新时间:2023-12-04 14:49:27 26 4
gpt4 key购买 nike

我尝试了很多方法来覆盖 :destroy 方法的行为,但没有任何效果。我首先使用了 act_as_paranoia 插件,但它不适用于 has_many 中的模型:通过关联。

我想覆盖 :destroy 方法只是为了做这样的事情:

  def destroy
_run_destroy_callbacks { delete }
end

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

也就是说,我只想更新另一个字段(状态为 0)而不是销毁记录本身。

最佳答案

你有没有尝试过?:

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

编辑:根据评论,可能还有其他东西在起作用,它可能只是关联定义上的 (:dependent=>'') 名称——或者如果它是 HABTM,它可能根本不起作用。也许 this info on delete and destroy through associations会有帮助吗?粘贴以下相关部分:

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

关于ruby-on-rails - rails : how to overwrite :destroy method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9333159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com