gpt4 book ai didi

ruby-on-rails - Rails has_many 使用关联 ID 不在销毁时调用回调

转载 作者:行者123 更新时间:2023-12-02 04:04:50 24 4
gpt4 key购买 nike

has_many 关系更新且记录被销毁时,不会触发 after_commit 回调。

我有关系

class Expertise
has_many :doctor_expertises
has_many :doctor_profiles, through: :doctor_expertises

class DoctorExpertise
belongs_to :doctor_profile
belongs_to :expertise

after_commit :do_something

def do_something
# not called when record destroyed
end

在我的 Controller 中,我使用以下方法来更新 has_many 关系

  def create
doc = DoctorProfile.find(params[:doctor_id])
doc.expertise_ids = params[:expertise_ids].select do |x|
x.to_i > 0
end
doc.save!

render json: doc.expertises
end

我知道我应该对关系使用updatedestroy。但是,为什么在记录被销毁时 after_commit 没有被调用?

我猜这与我设置 doc.expertise_ids 不触发回调的方式有关。但是,除了简短的 here 之外,我无法找到有关此方法的任何文档。 。是否有文件证实或否认这种怀疑,或者还有其他情况发生?

最佳答案

来自您链接的 RailsGuides:

直接自动删除连接模型,不会触发销毁回调。

虽然它没有说明 after_commit,但它很可能也没有被解雇

我认为您正在寻找的答案就在这里:

Howto use callbacks in a has_many through association?

您需要在 has_many 声明中使用 after_remove

关于ruby-on-rails - Rails has_many 使用关联 ID 不在销毁时调用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40004423/

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