加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:dependent => destroy,想要调用另一

发布时间:2020-12-17 01:46:09 所属栏目:百科 来源:网络整理
导读:我有一个完美运行的has_many:through模型. has_many :varietals has_many :grapes,:through = :varietals,:dependent = :destroy 我想调用另一个动作而不是:destroy.事实上,我不想取消项目或销毁它,我想将记录状态字段从1更新为0而不是销毁记录. 如何调用
我有一个完美运行的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方法以更新状态字段.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读