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:
- Keeping track of record modifications without changing other data.
- Triggering dependent callbacks that rely on timestamps.
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:
- Efficiency when updating timestamps for large datasets.
- Avoidance of triggering callbacks or validations, making it faster.
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
:
- Efficiency:
touch_all
executes a single query to update timestamps for all matching records, unliketouch
which executes a separate query for each record. - Speed:
touch_all
is significantly faster thantouch
for large datasets, as it avoids callbacks and validations. - Readability: Using
touch_all
makes code more concise and readable, especially when dealing with large datasets.
Further Considerations:
- When using
touch_all
, it’s important to be aware of any potential side effects, such as triggering callbacks or invalidating cached data. - In some cases, it may be desirable to use
touch
instead oftouch_all
for finer control over which records are updated. - It’s always a good idea to benchmark both methods to determine which one is the most efficient for a specific use case.