method
eager_load
v7.1.3.4 -
Show latest stable
-
0 notes -
Class: ActiveRecord::QueryMethods
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (11)
- 4.1.8 (0)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (38)
- 7.1.3.4 (0)
- What's this?
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.