Techioz Blog

previous_changes が after_commit で失われる

概要

      after_save do
        tracked_changes = self.previous_changes.select { |attribute, _| self.all_trackables.include?(attribute.to_sym) }
        puts "\e[38;5;208m#{tracked_changes}\e[0m"
      end
      after_commit do
        tracked_changes = self.previous_changes.select { |attribute, _| self.all_trackables.include?(attribute.to_sym) }
        puts "\e[38;5;206m#{tracked_changes}\e[0m"
      end

出力: 保存後:

{"name"=>[nil, "hamza"], "phone"=>[nil, "xxxxxxxxx"], "email"=>[nil, "[email protected]"]}
{"assignee_id"=>[nil, 3764], "client_type_id"=>[nil, 204], "classification_id"=>[nil, 2]}
{"primary_contact_id"=>[nil, 378115]}

コミット後:

{"primary_contact_id"=>[nil, 378115]}

追跡された変更はコミット後に失われます。余分なメモリを使用せずに after_save にある変更が必要です。なぜprevious_changesがafter_commitで失われるのか誰か教えてもらえますか? 保持される唯一の変更は、更新中の変更です。挿入の変更は after_commit で失われます。 after_commit と after_save の両方を試してみます。

解決策

previous_changes の仕組みは、前のトランザクションで変更された属性の変更のみを追跡することです。例えば -

これは、オブジェクト モデルにおけるprevious_changesのデフォルトの動作です。

保存後

コミット後