Rails模型 - 从未调用after_destroy

Ism*_*urg 4 activerecord ruby-on-rails ruby-on-rails-4

我在模型中使用after_destroy有些麻烦

这是这一个:

class Transaction < ActiveRecord::Base
  belongs_to :user
  delegate :first_name, :last_name, :email, to: :user, prefix: true

  belongs_to :project
  delegate :name, :thanking_msg, to: :project, prefix: true

  validates_presence_of :project_id

  after_save :update_collected_amount_in_project
  after_update :update_collected_amount_if_disclaimer
  after_destroy :update_collected_amount_after_destroy

  def currency_symbol
    currency = Rails.application.config.supported_currencies.fetch(self.currency)
    currency[:symbol]
  end

  private

  def update_collected_amount
    new_collected_amount = project.transactions.where(success: true, transaction_type: 'invest').sum(:amount)
    project.update_attributes(collected_amount: (new_collected_amount / 100).to_f) # Stored in € not cents inside projects table
  end

  def update_collected_amount_in_project
    update_collected_amount if transaction_type == 'invest' && success == true
  end

  def update_collected_amount_if_disclaimer
    update_collected_amount if transaction_type == 'invest' && self.changes.keys.include?('success') && self.changes.fetch('success', []).fetch(1) == false
  end

  def update_collected_amount_after_destroy
    update_collected_amount
  end
end
Run Code Online (Sandbox Code Playgroud)

当我使用类似的东西:

Transaction.last.delete
Run Code Online (Sandbox Code Playgroud)

它永远不会进入我的after_destroy,我试图包括一些输出,但没有.我不知道我是如何使用它的after_destroy,我也尝试了,我也before_destroy有同样的问题.after_save并且after_update工作完美.

Zac*_*ght 11

after_destroy回调不叫上delete.只有你打电话才会打电话给他们destroy,如下:

Transaction.last.destroy
Run Code Online (Sandbox Code Playgroud)

这实际上是两种方法之间的唯一区别.Delete绕过回调.

删除也不会执行任何:dependent关联选项.

原因是它从不实例化您要删除的任何活动记录对象,它只是对数据库执行SQL删除语句.