Created
December 13, 2012 10:17
-
-
Save a-chernykh/4275491 to your computer and use it in GitHub Desktop.
Undocumented options of doing eager loading in ActiveRecord
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 1st way - do it automatically | |
| # AR decides if it's better to use JOIN or separate query | |
| User.includes(:profile) | |
| # -> join or separate query | |
| # 2nd way - always use JOIN | |
| User.eager_load(:profile) | |
| # -> SELECT `users`.`id` AS t0_r0, ..., `profiles`.`user_id` AS t1_r1, ... FROM `users` LEFT OUTER JOIN `profiles` ON `profiles`.`user_id` = `users`.`id` | |
| # 3rd way - always do separate query | |
| User.preload(:profile) | |
| # -> SELECT * FROM users | |
| # -> SELECT * FROM profiles WHERE user_id IN (...) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Profile < ActiveRecord::Base | |
| belongs_to :user | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class User < ActiveRecord::Base | |
| has_one :profile | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment