views:

427

answers:

2
A: 

You'll have to give us the model relationship and sql generated before we can begin to answer this question unfortunately.

rabble
sorry, i've now included that info in the question
Luke
+3  A: 

The reason they generate two different SQL queries is that Rails, by default, tries to optimize your SQL queries for fewer joins. When you include a list of conditions as part of your find that require the use of other tables then of course the resulting SQL has to include a join. But if all you're asking to do is to pre-populate objects with relationships to the objects you're retrieving then Rails figures it's more efficient to perform several fast queries rather than one big slow query.

Note that this does not cause an N+1 problem, because Rails will try to load all of the associated records in a single query.

Brian Guthrie
Thanks, this makes sense. So your recommendation would be to just let ActiveRecords do its thing?
Luke
Probably, yeah. By all means, write custom SQL if you need to; ActiveRecord can't solve all the world's problems. But in this particular case there is, in fact, a reason for the madness.
Brian Guthrie
Naturally. I was just really confused by the results of this simple join.Thanks!
Luke