As long as I can remember you could always eager load your associations in rails. If you wanted to find all your users companies, you could tell rails to do it in an efficient way.

There is no change in the code you write

User.all(:include => :company)

The SQL it used to generate was:

SELECT
  `users`.`id`      AS t0_r0
  `users`.`email   AS t0_r1
  . . .
FROM
  `users`
  LEFT OUTER JOIN `companies` ON `companies`.id = `users`.company_id

Fine, that isn’t really news, but now active_record splits that sql statement up into two statements.

SELECT * FROM `users`;
SELECT * FROM `companies`
  WHERE `companies`.id IN ('1','2', . . . );

Apparently this will be faster in most cases. I don’t have anything to say about that but, there are two interesting things I want to show you. They both involve :conditions.

If you put conditions on the users table it still generates two queries.

User.all(:include => :company,
  :conditions => "`users`.`email` LIKE '%gmail%'")
SELECT * FROM `users`
  WHERE `users`.`email` LIKE '%gmail%';
SELECT * FROM `companies`
  WHERE `companies`.id IN ('1','2', . . . );

But if you put conditions on the companies table it fails over to the old style and generates one statement

User.all(:include => :company,
  :conditions => "`companies`.`name` LIKE '%google%'")
SELECT
  `users`.`id`      AS t0_r0
  `users`.`email   AS t0_r1
  . . .
FROM
  `users`
  LEFT OUTER JOIN `companies` ON `companies`.id = `users`.company_id
WHERE
  `companies`.`name` LIKE '%google%'

I don’t know if they have to do it that way to get the correct results or what. But I thought it was interesting.

Post Information

Tags:

We're Reading

Feeds/Syndication

One Response to “Rails 2.1 Eager Loading”

Leave a Reply