我正在尝试生成一个片段缓存(使用 Dalli/Memcached 存储),但是 key 是用“#”作为 key 的一部分生成的,所以 Rails 似乎没有意识到有一个缓存值并且正在命中数据库。
我在 View 中的缓存键如下所示:
cache([@jobs, "index"]) do
Controller 具有:
@jobs = @current_tenant.active_jobs
使用这样的实际 Active Record 查询:
def active_jobs
self.jobs.where("published = ? and expiration_date >= ?", true, Date.today).order("(featured and created_at > now() - interval '" + self.pinned_time_limit.to_s + " days') desc nulls last, created_at desc")
end
查看 rails 服务器,我看到缓存读取,但 SQL 查询仍在运行:
Cache read: views/#<ActiveRecord::Relation:0x007fbabef9cd58>/1-index
Read fragment views/#<ActiveRecord::Relation:0x007fbabef9cd58>/1-index (1.0ms)
(0.6ms) SELECT COUNT(*) FROM "jobs" WHERE "jobs"."tenant_id" = 1 AND (published = 't' and expiration_date >= '2013-03-03')
Job Load (1.2ms) SELECT "jobs".* FROM "jobs" WHERE "jobs"."tenant_id" = 1 AND (published = 't' and expiration_date >= '2013-03-03') ORDER BY (featured and created_at > now() - interval '7 days') desc nulls last, created_at desc
关于我可能做错了什么的任何想法?我确定它必须与 key 生成和 ActiveRecord::Relation 相关,但我不确定如何。
最佳答案
背景:
问题是每次运行代码时关系的字符串表示形式都不同:
|This changes|
views/#<ActiveRecord::Relation:0x007fbabef9cd58>/...
所以你每次都会得到一个不同的缓存键。
除此之外,不可能完全摆脱数据库查询。 (你的 own answer 是最好的)
解决方案:
生成一个有效的 key ,而不是这个
cache([@jobs, "index"])
做这个:
cache([@jobs.to_a, "index"])
这将查询数据库并构建一个模型数组,从中
cache_key
被检索。PS:我可以发誓使用在以前版本的 Rails 中工作的关系......
关于ruby-on-rails - 生成为 ActiveRecord::Relation 的 Rails 缓存键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15194270/