LoginSignup
9
0

More than 1 year has passed since last update.

更新日時を全部更新しないようにするためのupdate_attributeとupdate_columnsの違い

Last updated at Posted at 2022-12-22

🎅< WEBCAMP ENGINEER COMMUNITY Advent Calendar 2022 23日目の記事です。

背景

大量のテーブルのとあるカラムを全て更新しようと思いました。

ただ、テーブルのupdated_atが全部更新されてしまうのはちょっと怖いな...と思ったので良いメソッドがないか探したところ、ちょうどよく2種類用意されていたので、ここに簡単にまとめてみます📝

結論

https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute
こちらを読んでいただければ正確にわかります。

せっかくなので一部説明します。

update_attribute(name, value)

Updates a single attribute and saves the record. 
This is especially useful for boolean flags on existing records. Also note that

Validation is skipped.
Callbacks are invoked.
updated_at/updated_on column is updated if that column is available.

バリデーションはされず、コールバックは呼ばれ(カラム更新後に何かをするみたいな実装があれば、それを呼んでくれるのだと思います)、updated_atまたはupdated_onのカラムがあれば更新がされるようです。

今回の期待にはそぐわないですね。

update_columns(attributes)

# 中略

In particular:

Validations are skipped.
Callbacks are skipped.

updated_at/updated_on are not updated.

バリデーションもコールバックもスキップされ、updated_atまたはupdated_onのカラムがあっても更新されないようです。こちらを使用しました。

updated_atは、データの変化を追う際にキーとなるカラムになり得ます。今回前者のメソッドで実行していただ場合、全てのカラムが同じ時刻になってしまうのでちゃんと探してみて良かったです。

9
0
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
9
0