gpt4 book ai didi

ruby-on-rails - ActiveRecord 什么时候运行查询?

转载 作者:行者123 更新时间:2023-12-04 19:35:10 25 4
gpt4 key购买 nike

我对 ActiveRecord 何时运行它的查询很感兴趣,因为我记得读过 Rails 会通过在使用实际数据之前不执行查询来优化查询,我只是不确定如何证明这一点或在文档中找到它。我不能只在 Rails 控制台中运行这些行,因为它会在我输入时显式运行查询。我将在下面解释我的意思:

@stores = Store.where(active: true)
# Query should not have ran yet

@stores = @stores.includes(:owners)
# Query should not have ran yet

@stores.each { |store| store.do_something }
# So from this point forward, it should run
# Store.includes(:owners).where(active: true) all at once
# or it would have ran 3 queries instead of one.

我如何证明这一点,或者有人可以引导我找到正确的文档吗?

最佳答案

虽然我知道 Rails 会推迟执行查询,直到真正需要它们时,我还没有在文档中深入到这一部分。为了弄清楚运行了多少数据库查询,我使用了这个名为 db-query-matchers 的 gem。在我的 RSpec 测试中进行实验。

在你的情况下,我会做类似的事情:

it 'experiment 1' do
expect { @stores = Store.where(active: true) }.to make_database_queries(count: 0..3)
end

it 'experiment 2' do
expect do
@stores = Store.where(active: true)
@stores = @stores.includes(:owners)
end.to make_database_queries(count: 0..3)
end

it 'experiment 3' do
expect do
@stores = Store.where(active: true)
@stores = @stores.includes(:owners)
@stores.each { |store| store.do_something }
end.to make_database_queries(count: 0..3)
end

关于ruby-on-rails - ActiveRecord 什么时候运行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50240207/

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