eager_load(*args) public

Specify associations args to be eager loaded using a LEFT OUTER JOIN. Performs a single query joining all specified associations. For example:

users = User.eager_load(:address).limit(5)
users.each do |user|
  user.address.city
end

# SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ... FROM "users"
#   LEFT OUTER JOIN "addresses" ON "addresses"."id" = "users"."address_id"
#   LIMIT 5

Instead of loading the 5 addresses with 5 separate queries, all addresses are loaded with a single joined query.

Loading multiple and nested associations is possible using Hashes and Arrays, similar to #includes:

User.eager_load(:address, friends: [:address, :followers])
# SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ... FROM "users"
#   LEFT OUTER JOIN "addresses" ON "addresses"."id" = "users"."address_id"
#   LEFT OUTER JOIN "friends" ON "friends"."user_id" = "users"."id"
#   ...

NOTE: Loading the associations in a join can result in many rows that contain redundant data and it performs poorly at scale.

Show source
Register or log in to add new notes.