Search code examples
ruby-on-railsmongoid

undefined method `eager_load' for Book:Class (NoMethodError)


I getting an error using rails 6 ( Ruby 3.1.2) with mongoid.

without the eager_load this will causes me a huge timeout and it affect the loading time and some times it gives a 500 status. but it's not working

Rails c Output :

irb(main):028:0> Book.eager_load(:user)
(irb):28:in `<main>': undefined method `eager_load' for Book:Class (NoMethodError)

Undefined method `eager_load' for Book:Class   
scope = Book.eager_load(:user)

Book Model:

class Book
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :user
  belongs_to :booking_slot_type, optional: true
...

User Model :

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include Geocoder::Model::Mongoid
  include Mongoid::Slug
  include Mongoid::Token
  
  has_many :books
  has_many :prescriptions
  has_many :sms_logs

  has_one :review

Solution

  • Use Book.includes(:user)

    You can also specify multiple relationships, like this:

    books = Book.includes(:address, :user)

    Loading nested relationships is possible using a Hash:

    users = User.includes(:address, friends: [:address, :followers])