sgillesp
sgillesp

Reputation: 41

Mongoid overload of initialize

I ran into this error using Mongoid with a rails model:

NoMethodError: undefined method `[]' for nil:NilClass

To simplify, my classes were declared as follows:

class Fruit
    include Mongoid::Document

    field :name, type: String

    def initialize
        self.name = 'fruit'
    end
end

Initially I couldn't figure out where this was coming from so I started paring things down. Taking the Mongoid::Document include out fixed the problem (but obviously wasn't ideal). After further massaging Google I found this discussion:

https://github.com/mongoid/mongoid/issues/1678

...which described the same problem. As I would like to use an initialize mechanism to set instance variables in subclasses, I came up with this solution:

class Fruit
    include Mongoid::Document

    field :name, type: String, default: ->{ self.do_init }

    def do_init
        self.name = 'fruit'
    end
end

This works, but seems less than ideal. Then again, maybe it's OK. I wanted to post this because a) I had a difficult time finding a description of a similar problem, and b) I though this was poorly documented in mongoid.

As I understand this, the Mongoid gem overloads initialize, and my attempt at overriding initialize re-overloads and breaks the Mongoid::Document initialization process.

Upvotes: 4

Views: 1354

Answers (1)

tyler
tyler

Reputation: 589

I have been trying to solve this problem for hours and just figured it out. You need to call super at the beginning of your initialize method. For example,

class Fruit
    include Mongoid::Document

    field :name, type: String

    def initialize
        super
        self.name = 'fruit'
    end
end

Unfortunately I do not know enough about ruby to give you an explanation of why this is needed. I don't completely understand how super works in this case, given that the super class is just Object.

Upvotes: 5

Related Questions