1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ActiveRecord で作成・更新状態を確認するメソッド

Last updated at Posted at 2022-04-21

よく使う割に忘れてしまうので、メモしておく。

前提

  • Rails 6.1.7
  • レコードを更新する際に、変更内容をログ出す時に使うこと多い

新しいレコードか

# 保存前
user.new_record?
=> true

# 保存後(id値は変更されない前提)
user.id_before_last_save.nil?
=> true

オブジェクトが更新されたか

# 保存前
user.has_changes_to_save?
=> true

# 保存後
user.saved_changes?
=> true

どの属性が更新されたか

# 保存前
user.changed_attribute_names_to_save
=> ["name"]

# 保存後
user.saved_changes.keys
=> ["name"]

ある属性が更新されたか

# 保存前
user.will_save_change_to_name?
=> true

# 保存後
user.saved_change_to_name?
=> true

ある属性の更新前の値は何か

# 保存前
user.name_in_database
=> "foo"

# 保存後
user.name_before_last_save
=> "foo"

ある属性がどのように更新されたか

# 保存前
user.changes_to_save
=> {"name"=>["foo", "bar"]}

# 保存後
user.saved_changes
=> {"name"=>["foo", "bar"]}

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?