module Jennifer::QueryBuilder::EagerLoading
Overview
Includes methods required for associations eager loading.
Eager loading is a way to find objects of a certain class and a number of named associations. It is one of the easiest ways to prevent the dreaded N+1 problem in which fetching 100 posts that each need to display their author triggers 101 database queries. Through the use of eager loading, the number of queries will be reduced from 101 to 2.
Direct including types
Defined in:
jennifer/query_builder/eager_loading.crInstance Method Summary
- #_select_fields : Array(Criteria)
-
#eager_load(*names, **deep_relations)
Adds to select statement given relations (with corresponding
LEFT OUTER JOIN
) and loads them from results. -
#includes(*names, **deep_relations)
Specify relationships to be included in the result set.
- #multi_query_relation_tree
- #nested_relation_tree : NestedRelationTree
-
#preload(*names, **deep_relations)
Alias for includes.
-
#with_relation(names : Array)
Mark recently added join to be used to retrieve for relations given in names.
-
#with_relation(*names)
Mark recently added join to be used to retrieve for relations given in names.
Instance Method Detail
Adds to select statement given relations (with corresponding LEFT OUTER JOIN
) and loads them from results.
Contact.all.eager_load(:addresses)
# SELECT contacts.*, addresses.*
# FROM users
# LEFT JOIN addresses ON addresses.contact_id = contacts.id
You can specify nested relationships same way as in #includes
:
Contact.all.includes(:addresses, friends: %i(addresses followers))
Specify relationships to be included in the result set.
All specified relationships are loaded in a separate queries.
Contact.all.includes(:addresses)
Contact.all.includes(:addresses, friends: %i(addresses followers))
Mark recently added join to be used to retrieve for relations given in names.
This allows to specify custom JOIN and load results into specified relation.
Contact.all.join(Address) { and(Address._contact_id == Contact._id, Address._main) }.with_relation([:addresses])
Mark recently added join to be used to retrieve for relations given in names.
This allows to specify custom JOIN and load results into specified relation.
Contact.all.join(Address) { and(Address._contact_id == Contact._id, Address._main) }.with_relation(:addresses)