在after_commit中跟踪模型更改:on =>:创建回调

时间:2023-02-04 01:19:33

Is there a way to track changes to model on after_commit when a record is created? I have tried using dirty module and was able to track changes when the record was updated, but when record is created changes are not recorded.

有没有办法在创建记录时跟踪after_commit上的模型更改?我尝试过使用脏模块,并且能够在更新记录时跟踪更改,但是在创建记录时,不会记录更改。

1 个解决方案

#1


45  

You can't use the rails changed? method, as it will always return false. To track changes after the transaction is committed, use the previous_changes method. It will return a hash with attribute name as key. You can can then check if your attribute_name is in the hash:

你不能使用导轨改变?方法,因为它总是返回false。要在提交事务后跟踪更改,请使用previous_changes方法。它将返回一个带有属性名称作为键的哈希。然后,您可以检查您的attribute_name是否在哈希中:

after_commit :foo

def foo
 if previous_changes[attribute_name]
   #do your task
 end
end

#1


45  

You can't use the rails changed? method, as it will always return false. To track changes after the transaction is committed, use the previous_changes method. It will return a hash with attribute name as key. You can can then check if your attribute_name is in the hash:

你不能使用导轨改变?方法,因为它总是返回false。要在提交事务后跟踪更改,请使用previous_changes方法。它将返回一个带有属性名称作为键的哈希。然后,您可以检查您的attribute_name是否在哈希中:

after_commit :foo

def foo
 if previous_changes[attribute_name]
   #do your task
 end
end