user1130176
user1130176

Reputation: 1864

mongoid 6.1.0 eager loading throwing weird error undefined method each for nil

i have two basic mongoid classes:

class CaseType
    include Mongoid::Document

    has_many :case_type_field_sets

...


class CaseTypeFieldSet
  include Mongoid::Document
...
  belongs_to :case_type
...

in the console, I do something simple like:

CaseType.includes(:case_type_field_sets).count

this works fine.

If i do

CaseType.includes(:case_type_field_sets).first

it throws an error:

NoMethodError: undefined method `each' for nil:NilClass
from /(path)/lib/mongoid/relations/eager/base.rb:92:in `set_on_parent'

Any idea what's going on here?

Upvotes: 1

Views: 581

Answers (1)

user1130176
user1130176

Reputation: 1864

This happens when you manually declare the foreign key, which is a force of habit if you're building a mongo app after being in the habit of building a mysql app. So if you have manual declarations like:

belongs_to :parent
field :parent_id, type: String

Removing that foreign key declaration, b/c mongoid takes care of this for you, will fix the "undefined method each for nil" issue.

Upvotes: 2

Related Questions