Rails 5.2 关系生成两个查询的缓存键

Rails 5.2 cache key for relations generating two queries

我有一个使用片段缓存的视图 ActiveRecord 关系,例如

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

我看到在这种情况下生成了两个数据库查询

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

我期待第一个,它通常是一个更有效的查询。没想到第二个。

如果我改为使用:

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

然后我只得到具有相同结果缓存键的第一个查询。

是bug还是我做错了什么?

编辑:缩小到发生这种情况的地方:参见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.

是的,这看起来确实像一个错误。希望这会是 fixed on this PR, since my own PR for a stopgap fix was rejected