19
12

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 5 years have passed since last update.

Railsでモデルのupdate_atのみを更新したい場合

Last updated at Posted at 2018-06-16
  • touchメソッドを使います
ruby
user = User.last

user.updated_at
# => Sat, 16 Jun 2018 12:45:43 JST +09:00

user.touch
=> true

user.updated_at
# => Sat, 16 Jun 2018 12:47:03 JST +09:00
# updated_atが更新されている

他の値は変えたくないが、更新日時だけ更新したいときに便利!

ちなみに引数で指定すればupdated_at以外にも更新できるみたいです、試しにcreated_atを更新してみます。

ruby
user.created_at
# => Fri, 15 Jun 2018 17:36:48 JST +09:00

user.touch(:created_at)
# => true

user.created_at
# => Sat, 16 Jun 2018 12:51:04 JST +09:00
# created_atが更新されている

いろいろ応用が利きそうですね。

ただこのメソッドはバリデーションしてくれないので、更新する値にバリデーションが必要な場合は注意してください。

参考

19
12
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
19
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?