after_commitで変更されたカラムの情報を取得する
2458 ワード
callbackで変更されたカラムの情報を利用したい場合、
after_saveまではchanges で取得できるが
after_commit では当然だが変更が完了しているため取得できない。
previous_changesを使うことで取得できる
class User < ApplicationRecord
after_save do
p "after_save"
p "changes"
p self.changes
p "previous_changes"
p self.previous_changes
end
after_commit do
p "after_commit"
p "changes"
p self.changes
p "previous_changes"
p self.previous_changes
end
end
u = User.find 1
u.name = "BBB"
u.save
# "after_save"
# "changes"
# {"name"=>["AAA", "BBB"], "updated_at"=>[Tue, 09 Aug 2016 10:57:44 UTC +00:00, Tue, 09 Aug 2016 10:58:51 UTC +00:00]}
# "previous_changes"
# {}
# "after_commit"
# "changes"
# {}
# "previous_changes"
# {"name"=>["AAA", "BBB"], "updated_at"=>[Tue, 09 Aug 2016 10:57:44 UTC +00:00, Tue, 09 Aug 2016 10:58:51 UTC +00:00]}
Author And Source
この問題について(after_commitで変更されたカラムの情報を取得する), 我々は、より多くの情報をここで見つけました https://qiita.com/nog/items/1174ac3a9b841a250085著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .