Mongoid超载的初始化
问题描述:
我跑进使用Mongoid与轨道模型此错误:Mongoid超载的初始化
NoMethodError: undefined method `[]' for nil:NilClass
为了简化,我的课被宣布如下:
class Fruit
include Mongoid::Document
field :name, type: String
def initialize
self.name = 'fruit'
end
end
起初我想不出这是从哪里来的,所以我开始削减一些东西。采取Mongoid :: Document包括解决问题(但显然不是理想的)。进一步按摩谷歌后,我发现这个讨论:
https://github.com/mongoid/mongoid/issues/1678
...这说明了同样的问题。当我想用一个初始化的机制来设置实例变量在子类中,我想出了这个解决方案:
class Fruit
include Mongoid::Document
field :name, type: String, default: ->{ self.do_init }
def do_init
self.name = 'fruit'
end
end
这工作,但似乎不太理想。然后再一次,也许没关系。我想发布这个是因为:a)我很难找到类似问题的描述,b)我虽然在mongoid中没有很好的记录。
据我所知,Mongoid gem重载初始化,并且我试图覆盖初始化重新重载并打破了Mongoid :: Document的初始化过程。
答
我一直试图解决这个问题几个小时,只是想通了。你需要在初始化方法开始时调用super。例如,
class Fruit
include Mongoid::Document
field :name, type: String
def initialize
super
self.name = 'fruit'
end
end
不幸的是,我不知道红宝石给你一个解释为什么这是必要的。考虑到超类仅仅是Object,我并不完全理解超级作品在这种情况下的作用。
对;这是我输入的一个例子。编辑以纠正以上。感谢您收到 – sgillesp
before_create可能是最接近于Object :: initialize pattern.thanks! – sgillesp