ruby-on-rails – Rails:dependent => destroy,想要调用另一个动作而不是destroy

我有一个完美运行的has_many:through模型.

has_many :varietals
  has_many :grapes,:through => :varietals,:dependent => :destroy

我想调用一个动作而不是:destroy.事实上,我不想取消项目或销毁它,我想将记录状态字段从1更新为0而不是销毁记录.

如何调用自定义方法而不是销毁?我想我可以在模型中做到这一点……谢谢.

这个方法放在哪里?在主模型或模型中,记录将被销毁?

编辑:

我很抱歉,但我认为我没有解释我的问题.我的问题不仅仅是在主模型被销毁之后的某些东西.我想在Varietal模型中自定义destroy动作,即使主记录没有被破坏.

就像是:

class Varietal < ActiveRecord::Base

    private
      def destroy
        self.update_attributes(:status => 0)
      end
end

实际上这个动作没有被称为……

解决方法

has_many:dependent仅限于几个选项.根据 documentation

:dependent If set to :destroy all the associated objects are destroyed
alongside this object by calling their destroy method. If set to
:delete_all all associated objects are deleted without calling their
destroy method. If set to :nullify all associated objects’ foreign
keys are set to NULL without calling their save callbacks. If set to
:restrict this object raises an ActiveRecord::DeleteRestrictionError
exception and cannot be deleted if it has any associated objects.

If using with the :through option,the association on the join model
must be a belongs_to,and the records which get deleted are the join
records,rather than the associated records.

看起来您需要更改destroy方法以更新状态字段.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...