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 ...
Show source
Register or log in to add new notes.