Mongoid::Includes
improves eager loading in Mongoid, supporting polymorphic associations, and nested eager loading.
Album.includes(:songs).includes(:musicians, from: :band)
Band.includes(:albums, with: ->(albums) { albums.gt(release: 1970) })
# The library supports nested eager loading using :from for terseness,
# but you can manually include nested associations using the :with option.
released_only = ->(albums) { albums.where(released: true) }
Musician.includes(:band, with: ->(bands) { bands.limit(2).includes(:albums, with: released_only) })
Since you can modify the queries for the associations, you can use only
and make your queries even faster:
Band.includes :musicians, with: ->(musicians) { musicians.only(:id, :name) }
- Avoid N+1 queries and get better performance.
- No boilerplate code is required.
- Modify the queries for related documents at will.
Add this line to your application's Gemfile and run bundle install
:
gem 'mongoid_includes'
Or install it yourself by running:
gem install mongoid_includes
The gem is available as open source under the terms of the MIT License.
To run the full test suite locally:
bundle install
bundle exec rspec
# or use the bundled binary
bin/rspec
To run the tests against the Mongoid 8 matrix (this project provides a separate Gemfile at gemfiles/mongoid8.gemfile
), set BUNDLE_GEMFILE
to that file before installing or running the suite:
# install gems for the mongoid8 Gemfile
BUNDLE_GEMFILE=gemfiles/mongoid8.gemfile bundle install
# run the specs using that Gemfile
BUNDLE_GEMFILE=gemfiles/mongoid8.gemfile bundle exec rspec
# or
BUNDLE_GEMFILE=gemfiles/mongoid8.gemfile bin/rspec
If you only need to run a single spec file while using the alternate Gemfile, pass the path to rspec
as usual, for example:
BUNDLE_GEMFILE=gemfiles/mongoid8.gemfile bundle exec rspec spec/mongoid/includes/criteria_spec.rb
Contributions are welcome. If you'd like to report a bug, suggest an improvement, or submit a patch, please follow these steps:
-
Fork the repository on GitHub.
-
Create a feature branch from
master
(or from the branch you're targeting):git switch -c my-feature-branch
-
Make your changes. Add or update tests when appropriate.
-
Run the test suite locally to ensure everything passes:
bundle install bundle exec rspec
-
Commit your changes with a clear message and push your branch to your fork:
git add -A git commit -m "Short, descriptive message" git push origin my-feature-branch
-
Open a Pull Request against the
master
branch of this repository. In your PR description, explain the problem, what you changed, and any notes about compatibility or required steps.