【问题标题】:after_commit fires but attribute changes are not capturedafter_commit 触发但未捕获属性更改
【发布时间】:2017-06-07 13:12:26
【问题描述】:

所以我遇到了一些奇怪的事情,需要帮助

我有以下三个模型,它们的关系如下图所示

class Assignment < ActiveRecord::Base
  belongs_to :case_status
  has_one :application, :through => :case_status, :autosave => false 
  after_create :update_status

  def update_status
    self.case_status.update_attributes!({loan_case_id: update_case_status_id})
  end
end

class CaseStatus < ActiveRecord::Base
  belongs_to: application
  has_many :assignments, :dependent => :destroy
  accepts_nested_attributes_for :assignments,
                                :allow_destroy => true,
                                reject_if: proc { |attr| attr["lender_id"].blank? && attr["banker_id"].blank? }

  after_commit :catch_previous_changes,on: :update

  def catch_previous_changes
    self.previous_changes
  end
end

class Application < ActiveRecord::Base
  has_one :case_status, :dependent => :destroy
end

基本上,当创建分配时,有一个方法可以更新 case_status 模型上该记录的loan_case_id,但是当调用self.versions 代码时,它始终为空。

但是,当我在 rails 控制台上检查记录时,数据已经更新,这让我了解到 after_commit 调用正在被触发,但比先前更改属性 loan_case_id 的线程提前了一些。

现在我不知道如何调试它以了解为什么会发生这种情况,因为它仅在通过 after_create 方法完成 d 更新时发生。 loan_case_id 被更新的任何其他形式在调用self.previous_changes 时总是有数据。

【问题讨论】:

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


    【解决方案1】:

    你不能从after_commit得到任何脏改动,你必须使用around_save,类似这样:

    class CaseStatus < ActiveRecord::Base
      # all other code removed for brevity
    
      around_save :catch_previous_changes, on: :update
    
      def catch_previous_changes
        # see what attributes changed
        yield
        if persisted?
          # maybe do so other stuff if everything is ok
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2011-02-13
      • 2018-07-21
      • 1970-01-01
      • 2014-06-14
      • 2020-10-22
      • 2011-02-08
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      相关资源
      最近更新 更多