【问题标题】:Mongoid 3.1.4 undefined method 'has_key?' when calling 'Document.create'Mongoid 3.1.4 未定义方法'has_key?'调用“Document.create”时
【发布时间】:2013-06-07 01:38:48
【问题描述】:

我在尝试使用 Mongoid (v 3.1.4) 将(非常简单的)实体持久保存到 MongoDB (v 2.4.4) 时遇到问题。我在 OS X 上使用 MRI 和 Ruby 2.0.0-p195。

这是我的课程(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

最后一句话让我打招呼

[...]mongoid/attributes.rb:320:in 'method_missing': 未定义的方法 `has_key?'对于 nil:NilClass (NoMethodError)

这是我的“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

在创建数据库时,与数据库实例的连接似乎正常(“rbtest”),但是集合和文档失败。我已经尝试过“创建!”和“安全。保存!”无济于事。

我尝试实现 has_key?方法,我找不到任何文档,所以我在这里有点茫然。

一如既往,非常感谢任何帮助。

问候,


更新——解决方案:

@Frederik Cheung 的回答很到位。这是工作代码(根据@mu-is-too-short 的建议更新)

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!

【问题讨论】:

  • 你是对的,至少根据官方文档:D 更新了我的帖子。谢谢!

标签: ruby mongoid mongodb-ruby


【解决方案1】:

问题在于您的 initialize 方法:您正在覆盖 mongoid 提供的方法,因此未设置一些 mongoid 的内部结构。

您需要删除您的初始化方法或通过 super 调用 mongoid 的实现

【讨论】:

  • 你太棒了。非常感谢!
猜你喜欢
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多