Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
11
Help us understand the problem. What is going on with this article?
@ko30005

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

More than 1 year has passed since last update.
  • 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が更新されている

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

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

参考

11
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ko30005

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
11
Help us understand the problem. What is going on with this article?