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 running:
gem install mongoid_includes
The gem is available as open source under the terms of the MIT License.