Search code examples
ruby-on-railscachingactiverecordactivesupport

Rails 5.2 cache key for relations generating two queries


I have a view using fragment caching for an ActiveRecord relation, e.g.

<% cache MyModel.all do %>
...
<% end %>

I see two DB queries generated in this case

  1. SELECT COUNT(*) AS "size", MAX("my_model"."updated_at") AS timestamp FROM "my_model"
  2. SELECT "my_model".* from "my_model"

I expect the first one, and it's usually a much more efficient query. I did not expect the second one.

If I instead use:

<% cache ActiveSupport::Cache.expand_cache_key(MyModel.all) do %>
...
<% end %>

then I get only the first query with the same resulting cache key.

Is it a bug or am I doing something wrong?

EDIT: narrowed down to where this happens: see https://github.com/rails/rails/pull/29092#issuecomment-437572543

when normalize_version is executed, the relation does not respond to cache_version, and therefore ends up being expanded with to_a. So essentially, calling Product.all.to_a and then for each object calling cache_version, which returns nil.


Solution

  • Yes, this does look like a bug. Hopefully this would be fixed on this PR, since my own PR for a stopgap fix was rejected