Efficient Timestamp Management with Touch_all

Timestamps are a crucial part of any data model, helping track when records were created or modified. ActiveRecord provides convenient methods to manage timestamps: touch and touch_all.

Understanding touch

touch updates the updated_at timestamp of a single record. It’s useful for:

1
2
3
4
post = Post.find(1)
post.touch

# Updated at timestamp is updated

To manually update timestamps of multiple posts using touch, we can use a loop:

1
2
3
4
5
6
7
posts = Post.where(published: true)

posts.each do |post|
  post.touch
end

# The 'updated_at' timestamps of published posts are updated

Exploring touch_all

touch_all updates the updated_at timestamps of all records in a relation. Introduced in Rails 6, it offers:

1
2
3
4
5
6
7
# Using `where` clause to filter posts
posts = Post.where(published: true)

# Updates timestamps for all matching posts
posts.touch_all

# Updated at timestamps for all selected posts are updated

To update timestamps of all published posts more efficiently, we can use touch_all:

1
2
3
4
5
posts = Post.where(published: true)

posts.touch_all

# The 'updated_at' timestamps of published posts are updated

Advantages of using touch_all:

Further Considerations: