删除关联的has_and_belongs_to_many记录时触发回调

时间:2015-10-22 04:06:43

标签: ruby-on-rails activerecord

当清洁工从工作中移除但我们尝试过的回调(after_saveafter_commit)都没有被触发时,我们会尝试捕获。

我怀疑方法Job#release!触发数据库查询而不涉及Active Record。

如何在清理工作被删除后触发create_vacant_availabilities回调?

class Job < ActiveRecord::Base
  has_many :assignments
  has_many :cleaners, through: :assignments

  after_save :create_vacant_availabilities
  def create_vacant_availabilities
    debugger # doesn't get triggered when calling release!
  end

  def release!(cleaner = nil)
    if cleaner
      self.cleaners.delete(cleaner)
    else
      self.cleaners = []
    end
  end
end  

1 个答案:

答案 0 :(得分:1)

创建或销毁Assignment时,它不会更改与其配对的Job

您可以选择两种方式。

首先,您可以使用touch: trueFrom the Rails API ...

  

<强>:触摸

     

如果为true,则在保存或销毁此记录时将触摸关联对象(设置为当前时间的updated_at / on属性)。如果指定符号,除了updated_at / on属性外,该属性将使用当前时间进行更新。

...这意味着你会想要像

这样的东西
class Assignments
  belongs_to :job, touch: true

请注意,这不会触发after_save上的Job,因此您需要将其设为an after_touch callback

另一种可能性是Assignment上的a before_destroy callback

class Assignment
  belongs_to :job
  before_destroy :create_vacant_abilities_on_job

  def create_vacant_abilities_on_job
    self.job.create_vacant_abilities
  end

根据create_vacant_abilities背后的逻辑,您可能希望这是around_destroyafter_destroy回调。

相关问题