Skip to content

Instantly share code, notes, and snippets.

@a-chernykh
Created December 13, 2012 10:17
Show Gist options
  • Select an option

  • Save a-chernykh/4275491 to your computer and use it in GitHub Desktop.

Select an option

Save a-chernykh/4275491 to your computer and use it in GitHub Desktop.
Undocumented options of doing eager loading in ActiveRecord
# 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 (...)
class Profile < ActiveRecord::Base
belongs_to :user
end
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