Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
available_records
argument to Associations::Preloader
Sometimes when we are preloading associations on records, we already have the association objects loaded in-memory. But the Preloader will go to the database to fetch them anyways because there is no way to tell it about these loaded objects. This PR adds a new `available_records` argument to supply the Preloader with a set of in-memory records that it can use to fill associations without making a database query. `available_records` is an array of ActiveRecord::Base objects. Mixed models are supported. Preloader will use these records to try to fill 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) as we must query the database to do an exhaustive lookup for collections (i.e. :has_many). It also requires the query to have no scopes as scopes can filter associations even if they are already in memory. ```ruby comment = Comment.last post = Post.find_by(id: comment.post_id) all_authors = Author.all.to_a Preloader.new([comment], [:post, :author]).call Preloader.new([comment], [:post, :author], available_records: [post, all_authors]).call ``` Co-Authored-By: John Hawthorn <john@hawthorn.email>
- Loading branch information
Showing
5 changed files
with
113 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters