Subscribed unsubscribe Subscribe Subscribe

Rails - touchオプションでupdated_atを更新するヘ(^o^)ノ

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end
pry(main)> Post.find(1)
+----+-------------+------+-------------------------+-------------------------+
| id | title       | body | created_at              | updated_at              |
+----+-------------+------+-------------------------+-------------------------+
| 1  | sample post |      | 2014-11-21 13:54:14 UTC | 2014-11-21 13:54:14 UTC |
+----+-------------+------+-------------------------+-------------------------+

pry(main)> Post.find(1).comments.first.update(body: 'change comment')
pry(main)> Post.find(1)
+----+-------------+------+-------------------------+-------------------------+
| id | title       | body | created_at              | updated_at              |
+----+-------------+------+-------------------------+-------------------------+
| 1  | sample post |      | 2014-11-21 13:54:14 UTC | 2014-11-21 13:54:14 UTC |
+----+-------------+------+-------------------------+-------------------------+

commentを更新しても、Postのupdated_atは変更されないですよね?

では、touchオプションを指定してみましょう

class Comment < ActiveRecord::Base
  belongs_to :post,  touch: true
end

もう一度、commentを更新してみましょう

pry(main)> Post.find(1).comments.first.update(body: ' touch: true')
pry(main)> Post.find(1)
+----+-------------+------+-------------------------+-------------------------+
| id | title       | bosy | created_at              | updated_at              |
+----+-------------+------+-------------------------+-------------------------+
| 1  | sample post |      | 2014-11-21 13:54:14 UTC | 2014-11-21 14:05:16 UTC |
+----+-------------+------+-------------------------+-------------------------+

pry(main)> Post.find(1).comments.first
+----+-------------+-------------------------+-------------------------+---------+
| id | body        | created_at              | updated_at              | post_id |
+----+-------------+-------------------------+-------------------------+---------+
| 1  | touch: true | 2014-11-21 13:54:14 UTC | 2014-11-21 14:05:16 UTC | 1       |
+----+-------------+-------------------------+-------------------------+---------+

Postのupdated_atも更新されましたー

Viewでrender partialをキャッシュする場合とかに使えそうですね。

Happy Hacking٩( ‘ω’ )و