method
preload
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 (9)
- 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?
preload(*args)
public
Specify associations args to be eager loaded using separate queries. A separate query is performed for each association.
users = User.preload(:address).limit(5) users.each do |user| user.address.city end # SELECT "users".* FROM "users" LIMIT 5 # SELECT "addresses".* FROM "addresses" WHERE "addresses"."id" IN (1,2,3,4,5)
Instead of loading the 5 addresses with 5 separate queries, all addresses are loaded with a separate query.
Loading multiple and nested associations is possible using Hashes and Arrays, similar to #includes:
User.preload(:address, friends: [:address, :followers]) # SELECT "users".* FROM "users" # SELECT "addresses".* FROM "addresses" WHERE "addresses"."id" IN (1,2,3,4,5) # SELECT "friends".* FROM "friends" WHERE "friends"."user_id" IN (1,2,3,4,5) # SELECT ...