【问题标题】:after_destroy not called for linked tableafter_destroy 不为链接表调用
【发布时间】:2016-11-18 15:58:46
【问题描述】:

我有这些模型

class User < ActiveRecord::Base
  has_many :user_functions, :dependent => :destroy
  has_many :functions, :through => :user_functions
  accepts_nested_attributes_for :functions, allow_destroy: true

链接表的型号:

class UserFunction < ActiveRecord::Base
  belongs_to :user, inverse_of: :user_functions
  belongs_to :function, inverse_of: :user_functions
  after_destroy :unplan_items
  after_create :plan_items

当然还有功能模型,但这就像用户......

现在,当我在测试中执行以下操作时:

@user.functions = [@functions]
@user.save
expect(@user.planned_items.count).to eq(1)
@user.functions = []
@user.save

我注意到回调 after_destroy 没有被调用。为什么会这样,我该如何避免这种情况。每次销毁 UserFunction 时都需要执行某些步骤...

我相信这与:https://github.com/rails/rails/issues/7618(虽然我使用的是 rails 4.2.5)有关。 after_create 运行良好...

【问题讨论】:

  • 设置一个实例变量为[]然后保存与调用destroy是不一样的。
  • 对不起,我没有关注你。 @user 指的是某个用户,该用户具有通过 user_functions 表链接到他的 3 个函数。将函数设置为 [] 会有效地删除这些记录 (user_functions)。为什么这不经历那些毁灭?

标签: ruby-on-rails rails-activerecord


【解决方案1】:

目前 rails 使用 :delete_all 作为 has_many_through 的默认策略。只有当我们在关联上明确指定dependent: :destroy 时,它才会调用:destroy_all

如果您需要回调,文档提到了使用 has_many :through 的建议: 在此处查看建议:http://guides.rubyonrails.org/association_basics.html

如果你需要验证、回调,你应该使用 has_many :through 或连接模型上的额外属性。

所以目前在执行回调的after_createafter_destroy 之间存在不一致。

这在 GitHub 上发布的这两个问题中都有提到:

https://github.com/rails/rails/issues/7618

https://github.com/rails/rails/issues/27099

目前的解决方法是将:dependent =&gt; :destroy 明确放在:through 部分。这将确保使用回调。

class User < ActiveRecord::Base
  has_many :user_functions
  has_many :functions, :through => :user_functions, :dependent => :destroy
  accepts_nested_attributes_for :functions, allow_destroy: true

【讨论】:

    【解决方案2】:

    对于阅读此 2021+ 的任何人

    改变这个

    has_many :object_tags, :as => :taggable, :dependent => :destroy
    has_many :tags, :through => :object_tags
    

    到这里

    has_many :object_tags
    has_many :tags, :through => :object_tags, :dependent => :destroy
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多