我在模型中使用 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
当我使用类似的东西时:
Transaction.last.delete
它永远不会进入我的 after_destroy,我试图包含一些输出但什么也没有。我不知道我如何使用这个
after_destroy
是否有误,我也尝试过 before_destroy
并且我遇到了同样的问题。 after_save
和 after_update
完美运行。
最佳答案
after_destroy
回调不会在 delete
上调用。只有在调用 destroy
时才会调用它们,如下所示:
Transaction.last.destroy
这实际上是两种方法之间的唯一区别。
Delete
绕过回调。删除也不会执行任何
:dependent
关联选项。这样做的原因是它从不实例化您要删除的任何事件记录对象,它只是对数据库执行 SQL 删除语句。
关于ruby-on-rails - Rails 模型 - after_destroy 从未调用过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37306978/