gpt4 book ai didi

ruby-on-rails - 我看到了用于获取帖子的 sql 查询,即使它正在缓存数据

转载 作者:行者123 更新时间:2023-12-02 17:04:17 26 4
gpt4 key购买 nike

当我在我的 Controller 的操作中进行以下调用时,我可以看到我第一次加载页面时在控制台输出中看到输出“posts hitting the db”。

cache_key = "posts"
@posts = Rails.cache.fetch(cache_key, expires_in: 5.minutes) do
puts "posts hitting the db"
Post.include(:tags).where("post_status = 1").order("id desc")
end

如果我重新加载页面,我看不到“posts hitting the db”消息,但我仍然可以看到如下查询:

Processing by PostsController#index as HTML Rendering posts/index.html.erb within layouts/main Post Load (0.5ms) SELECT "posts".* FROM "posts" WHERE (post_status = 1) ORDER BY id desc ↳ app/views/posts/index.html.erb:6 Label Load (0.3ms) SELECT "tags".* FROM "tags" WHERE "tags"."id" = $1 [["id", 7]] ↳ app/views/posts/index.html.erb:6 Rendered posts/index.html.erb within layouts/posts (31.4ms) Completed 200 OK in 87ms (Views: 62.6ms | ActiveRecord: 8.2ms)

这是因为它正在缓存@posts 但由于@posts 对象实际上并没有被使用它甚至没有进行db 调用吗?那么当 View 页面执行@posts.each 时它会访问数据库吗?

例如,如果我删除了我的 View 页面中的所有 html,那么它根本不会访问数据库。

最佳答案

当你做的时候

Post.include(:tags).where("post_status = 1").order("id desc")

您实际上并没有调用数据库。您正在创建一个 ActiveRecord 范围——所以这就是您要缓存的内容。如果你想缓存数据库调用的结果,你需要做这样的事情:

cache_key = "posts"
@posts = Rails.cache.fetch(cache_key, expires_in: 5.minutes) do
puts "posts hitting the db"
Post.include(:tags).where("post_status = 1").order("id desc").all.to_a
end

相反,这使得 ActiveRecord 实际上用表数据填充@posts。

关于ruby-on-rails - 我看到了用于获取帖子的 sql 查询,即使它正在缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52460208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com