ruby-on-rails - Rails 模型 - after_destroy 从未调用过

标签 ruby-on-rails ruby-on-rails-4 activerecord

我在模型中使用 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_saveafter_update 完美运行。

最佳答案

after_destroy 回调不会在 delete 上调用。只有在调用 destroy 时才会调用它们,如下所示:

Transaction.last.destroy

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

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

这样做的原因是它从不实例化您要删除的任何事件记录对象,它只是对数据库执行 SQL 删除语句。

关于ruby-on-rails - Rails 模型 - after_destroy 从未调用过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37306978/

相关文章:

ruby-on-rails - 直接从 Rails 操作中使用 Rack 中间件

ruby-on-rails - 用于 strip 化非字母和非数字字符的正则表达式

ruby-on-rails - Rails 3 部署的最佳环境是什么

ruby-on-rails - 按 time desc 和 total_votes 呈现帖子

ruby-on-rails - 在 Rails 中设置用户和赏金之间的关联

ruby-on-rails - 如何使用 RSpec 为 JWT 验证应用程序制定请求规范

javascript - 在js文件内的ruby行中使用JS var

ruby-on-rails - 具有多种布局的 Rails Turbolinks

php - MySQL Codeigniter - $this->db->query 和 CLI 结果不匹配

ruby-on-rails - Rails ActiveRecord 对象 ID 是否保证单调递增?