为什么 Rails 不缓存 SQL 查询?
Why is Rails not caching SQL queries?
根据 Rails Guides:
Query caching is a Rails feature that caches the result set returned
by each query so that 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.
然后是在控制器的操作中执行相同查询的示例:
class ProductsController < ApplicationController
def index
# Run a find query
@products = Product.all
...
# Run the same query again
@products = Product.all
end
end
在我的视图布局中,我在几个地方调用了 Category.pluck(:id)
。在开发日志中,我多次看到这一行:
SELECT "categories"."id" FROM "categories"
即使我将此设置为 config.action_controller.perform_caching = true
用于开发,也会发生这种情况。为什么会这样?
查询缓存来自Rack。
运行 rake middleware
然后寻找 ActiveRecord::QueryCache
如果那是在你的中间件中,SQL 应该启用缓存,除非有其他东西将其关闭。
这里有一些关于查询缓存的文档:
http://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/QueryCache.html
和机架代码
http://api.rubyonrails.org/classes/ActiveRecord/QueryCache.html
根据 Rails Guides:
Query caching is a Rails feature that caches the result set returned by each query so that 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.
然后是在控制器的操作中执行相同查询的示例:
class ProductsController < ApplicationController
def index
# Run a find query
@products = Product.all
...
# Run the same query again
@products = Product.all
end
end
在我的视图布局中,我在几个地方调用了 Category.pluck(:id)
。在开发日志中,我多次看到这一行:
SELECT "categories"."id" FROM "categories"
即使我将此设置为 config.action_controller.perform_caching = true
用于开发,也会发生这种情况。为什么会这样?
查询缓存来自Rack。
运行 rake middleware
然后寻找 ActiveRecord::QueryCache
如果那是在你的中间件中,SQL 应该启用缓存,除非有其他东西将其关闭。
这里有一些关于查询缓存的文档:
http://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/QueryCache.html
和机架代码
http://api.rubyonrails.org/classes/ActiveRecord/QueryCache.html