Caching pagination collections is tricky. The usual trick of using the collection count and max updated_at
does mostly not apply!
As you said, the collection count is a given so kind of useless, unless you allow dynamic per_page
values.
The latest updated_at
is totally dependent on the sorting of your collection.
Imagine than a new record is added and ends up in page one. This means that one record, previously page 1, now enters page 2. One previous page 2 record now becomes page 3. If the new page 2 record is not updated more recently than the previous max, the cache key stays the same but the collection is not! The same happens when a record is deleted.
Only if you can guarantee that new records always end up on the last page and no records will ever be deleted, using the max updated_at
is a solid way to go.
As a solution, you could include the total record count and the total max updated_at
in the cache key, in addition to page number and the per page
value. This will require extra queries, but can be worth it, depending on your database configuration and record count.
Another solution is using a key that takes into account some reduced form of the actual collection content. For example, also taking into account all record id's.
If you are using postgres as a database, this gem might help you, though I've never used it myself.
https://github.com/cmer/scope_cache_key
And the rails 4 fork:
https://github.com/joshblour/scope_cache_key