开发者

Reducing 1001 queries into 2 in Ruby on Rails -- but can't?

You know sometimes you have 1000 records of Foo, and each one needs to access foo.bar, where bar is another model, then there will be 1000 queries more...

I thought the following l开发者_运维技巧ine, for 1000 records,

@foos = Foo.find(:all, :include => :bar)

used to make this into 1 query in some early version of Rails (by table join), but I don't know why the Rails 2 Foundation book says it is further optimized into 2 queries (why 2 queries is better than 1?):

SELECT "foos".* FROM "foos"
SELECT "bars".* FROM "bars" WHERE ("bars"."name" IN ('0001','0002', ... ))

but I don't know why in the view, when I print out foo.bar.title, it will still invoke 1 query per row as seen on the console log, so making it 1002 queries still. I thought somehow it should be 2 queries and that's it?


That looks wierd...

@foos = Foo.find(:all, :include => :bar)

then your code should be:

@foos.each do |foo|
  foo.bar.title
end

First law of demeter says you should have a method called bar_title in your foo class

@foos.each do |foo|
  foo.bar_title
end

Last please post a couple of the queries you see in the console. that is the hint that will solve why this is happening.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜