new
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (-6)
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1 (-31)
- 6.1.7.7 (0)
- 7.0.0 (38)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
new(records:, associations:, scope: nil, available_records: [], associate_by_default: true)
public
Eager loads the named associations for the given Active Record record(s).
In this description, ‘association name’ shall refer to the name passed to an association creation method. For example, a model that specifies belongs_to :author, has_many :buyers has association names :author and :buyers.
Parameters
records is an array of ActiveRecord::Base. This array needs not be flat, i.e. records itself may also contain arrays of records. In any case, preload_associations will preload all associations records by flattening records.
associations specifies one or more associations that you want to preload. It may be:
-
a Symbol or a String which specifies a single association name. For example, specifying :books allows this method to preload all books for an Author.
-
an Array which specifies multiple association names. This array is processed recursively. For example, specifying [:avatar, :books] allows this method to preload an author’s avatar as well as all of his books.
-
a Hash which specifies multiple association names, as well as association names for the to-be-preloaded association objects. For example, specifying { author: :avatar } will preload a book’s author, as well as that author’s avatar.
:associations has the same format as the :include method in ActiveRecord::QueryMethods. So associations could look like this:
:books [ :books, :author ] { author: :avatar } [ :books, { author: :avatar } ]
available_records is an array of ActiveRecord::Base. The Preloader will try to use the objects in this array to preload the requested associations before querying the database. This can save database queries by reusing in-memory objects. The optimization is only applied to single associations (i.e. :belongs_to, :has_one) with no scopes.