Arina
Arina

Reputation: 11

How to nested eager loading in mongoid?

Class Band
  include Mongoid::Document
  has_many :albums
end

Class Album
  include Mongoid::Document
  has_many :musics
  belongs_to :band
end

Class Music
  include Mongoid::Document
  belongs_to :album
end

when I do this, @bands = Band.includes(albums: [:musics])

albums are included successfully. musics are not included. bullet says "AVOID eager loading detected Band=>[:musics]" how can I include musics?

Upvotes: 1

Views: 1172

Answers (2)

Victor Cordeiro Costa
Victor Cordeiro Costa

Reputation: 2194

Well, Mongoid >= 8.0 already supports nested includes natively! ✔️

  • Syntax
Voucher.includes(:created_by, booking: [:unit])
  • Classes
class User
  include Mongoid::Document
end

class Unit
  include Mongoid::Document
end

class Booking
  include Mongoid::Document
  belongs_to :unit
  has_many :vouchers
end

class Voucher
  include Mongoid::Document
  belongs_to :booking
  belongs_to :created_by, class_name: 'User'
end

The new nested includes is shown as a solution to this ticket.

So, there is no need to use mongoid_includes gem if your Mongoid version is >= 8.0.

Upvotes: 1

Oshan Wisumperuma
Oshan Wisumperuma

Reputation: 1958

according this blog

Although Mongoid provides eager loading support out of the box, it has a few limitations:

  • No Nested: Only direct relations can be eager loaded.

  • No Polymorphic: Polymorphic relations can’t be included.

  • Criteria-only: It’s only possible to use eager loading with a Mongoid::Criteria object.

and also there is a solution.

Upvotes: 3

Related Questions