LoginSignup
8
9

More than 5 years have passed since last update.

after_commitで変更されたカラムの情報を取得する

Posted at

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]}
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9