微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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方法以更新状态字段.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐