Ruby ActiveRecord query_cache not being cleared after saved change to a model (upgrade active record 5 to 6)

huangapple go评论134阅读模式
英文:

Ruby ActiveRecord query_cache not being cleared after saved change to a model (upgrade active record 5 to 6)

问题

在将 active-record gem 从 5 升级到 6 后,出现了许多与模型相关的失败规范,即使模型调用 .save 并更新其数据的过程,模型也没有被刷新。
我找不到有关查询缓存如何被清除以及该行为是否在该版本中发生了变化的文档,但在 Changelog 上没有找到任何信息。

英文:

After updating the active-record gem from 5 to 6 there were lot of failing specs related to the models not being refreshed even if there were a process that calls .save in the model and updates its data.
I couldn't find any documentation on how the query_cache gets cleared and if that behavior changed in the version but found nothing on the Changelog.

答案1

得分: 1

Rails缓存指南中引用的内容:

查询缓存是Rails的一个功能,它缓存了每个查询返回的结果集。如果Rails在同一请求中再次遇到相同的查询,它将使用缓存的结果集,而不是再次对数据库运行查询。

[...]

当相同的查询第二次针对数据库运行时,实际上不会命中数据库。第一次结果从查询返回时,它被存储在查询缓存中(内存中),第二次从内存中提取。

但是,值得注意的是,查询缓存在操作开始时创建,操作结束时销毁,因此只在操作的持续时间内存在。[...]

这意味着Ruby on Rails会在请求的持续时间内缓存这些查询,并在请求结束时删除它们。这个行为已经存在很长时间了,例如,这里是Ruby on Rails 3.2的文档

也许,如果您分享一些演示您的问题的示例代码,我们将能够提供更详细的答案,解释为什么在升级后您的代码失败。

英文:

Quote from the Rails Guides about caching:

> Query caching is a Rails feature that caches the result set returned by each query. If Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
>
> [...]
>
> The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.
>
> However, it's important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. [...]

That means Ruby on Rails caches those queries for the duration of a request and deletes them at the end of the request. This behavior exists for a long time already, for example, here are the docs of Ruby on Rails 3.2.

Perhaps, if you shared some example code demonstrating your problem, we would be able to provide more detailed answers why your code is failing after the upgrade.

huangapple
  • 本文由 发表于 2023年2月24日 17:30:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定