Previously we could only pass a single record to these methods but now Rails 5 adds support for accepting a collection of records as well. For example,
or simply written as,
This works with stale? method too, we can pass a collection of records to it. For example,
To see this in action, let’s begin by making a request at /posts.
In the second request, we would send the ETag in If-None-Match header to check if the data has changed.
Since there’s no change, the server returned HTTP/1.1 304 Not Modified. If these requests were made from a browser, it would automatically use the version in its cache on the second request.
The second request was obviously faster as the server was able to save the time of fetching data and rendering it. This can be seen in Rails log,
Cache expires when collection of records is updated. For example, an addition of a new record to the collection or a change in any of the records (which changes updated_at) would change the ETag.
Now that Rails 5 supports collection of records in fresh_when and stale?, we have an improved system to cache resources and make our applications faster. This is more helpful when we have controller actions with time consuming data processing logic.