ruby previous_changes在after_commit中丢失

ecfsfe2w  于 5个月前  发布在  Ruby
关注(0)|答案(1)|浏览(48)
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_commit中丢失。我想要在不使用额外内存的情况下在after_save中的更改。有人能告诉我为什么这是previous_changesafter_commit中丢失吗?唯一保留的更改是正在更新的更改。插入更改在after_commit中丢失。我尝试after_commit和after_保存。

inn6fuwd

inn6fuwd1#

previous_changes的工作方式是它只跟踪在前一个事务中更改的属性更改。例如-
1.在插入过程中,所有将其值从nil更改为“something”的项目将由previous_changes使用新值和旧值进行跟踪。
1.在更新期间,只有更新的项目将由previous_change方法返回。
1.如果没有更新,它将返回{}。
这是previous_changes在对象模型上的默认行为。

后_保存

1.可以在交易过程中运行。
1.有时,由于保存的记录,可能会发生争用情况。

after_commit

1.这将只在数据库事务成功提交到db后运行。

相关问题