优化 Rails 急切加载查询以查找全部
在 Rails 2.3.5 应用程序中,我有类似以下模型的内容:
class Foo < ActiveRecord::Base
has_many :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
当我调用时
Foo.all(:include => :bars)
,我在控制台中看到以下查询:
SELECT * FROM "foos"
SELECT "bars".* FROM "bars" WHERE ("bars".foo_id IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21))
在 where 子句中包含所有 foo 的 id。
我想这不是一个最佳查询,因为 id 的数量可能很大,而且我需要预加载所有“条”。另外,实际上我拥有的不是两个模型,而是一系列模型。
有没有办法让急切加载查询就像
SELECT "bars".* FROM "bars"
我使用“查找全部”时一样?
In a Rails 2.3.5 application I've got something like the following models:
class Foo < ActiveRecord::Base
has_many :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
And when I'm calling
Foo.all(:include => :bars)
I see the following queries in console:
SELECT * FROM "foos"
SELECT "bars".* FROM "bars" WHERE ("bars".foo_id IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21))
with all the foo's ids in the where clause.
I guess this is not an optimal query while the number of ids may be large, and I need to preload all the 'bars'. Also, actually I've got not two models, but a chain of them.
Is there a way to make the eager loading query be like
SELECT "bars".* FROM "bars"
when I'm using find all?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上是一种优化,事实上,如果 id 的数量变多,Rails 会更改查询策略。
您还可以使用
:join
而不是使用:include
That's actually an optimization, in fact Rails changes the querying strategy if the number of id's goes high.
You could also use
:join
instead of using:include