views:

250

answers:

1

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?

+4  A: 

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

knoopx
Have a look here as well http://akitaonrails.com/2008/5/26/rolling-with-rails-2-1-the-first-full-tutorial-part-2 on 'Optimized Eager Loading' section
khelll
Thanks, knoopx!It came to me, that the eager loading must not be aware whether I'm actually loading all the table rows, or all foo's matching some condition (thus, WHERE clause will include not all foo's ids.)I'm now trying to find where Rails changes the querying strategy if the number of id's goes high just of curiosity.khelll, thanks for the link as well!
khustochka