I'm having a problem trying to use Mongoid (v 3.1.4) to persist a (really simple) entity to MongoDB (v 2.4.4). I'm using MRI and Ruby 2.0.0-p195 on OS X.
Here's my class (Person.rb):
require 'mongoid'
class Person
include Mongoid::Document
include Mongoid::Timestamps # currently can be ommitted
field :name, type: String
def initialize
# is empty
end
def name
@name
end
def name=(value)
@name = value
end
end
Mongoid.load!('config/mongoid.yml', :development)
user = Person.new
user.name = "John Doe"
user.create
That last sentence greets me with a
[...]mongoid/attributes.rb:320:in 'method_missing': undefined method `has_key?' for nil:NilClass (NoMethodError)
Here's my 'mongoid.yml':
development:
sessions:
default:
database: rbtest
hosts:
- localhost:27017
test:
sessions:
default:
database: test
hosts:
- localhost:27017
options:
consistency: :strong
max_retries: 1
retry_interval: 0
Connection to the DB instance seems ok as the DB is created ('rbtest') however, Collections and Documents fail. I've already tried with 'create!' and 'safely.save!' to no avail.
I tried implementing the has_key? method, for which I couldn't find any documentation, so I'm at a bit of a loss here.
As always, any help is much appreciated.
Regards,
@Frederik Cheung's answer was spot on. Here's the working code (updated with @mu-is-too-short's suggestion)
require 'mongoid'
class Person
include Mongoid::Document
field :name, type: String
end
Mongoid.load!('config/mongoid.yml', :development)
person = Person.new(:name => 'John Doe')
person.save!
The problem is your initialize
method: you are overriding the one provided by mongoid, so some of mongoid's internals aren't being setup.
You need to either remove your initialize method or call the mongoid's implementation via super