ruby - Mongoid 3.1.4 调用 'has_key?' 时未定义方法 'Document.create'

标签 ruby mongoid mongodb-ruby

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

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

最后一句话向我打招呼

[...]mongoid/attributes.rb:320:在“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!

最佳答案

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

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

关于ruby - Mongoid 3.1.4 调用 'has_key?' 时未定义方法 'Document.create',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16974966/

相关文章:

ruby - Applescript/Scripting Bridge 中的 QuickTimeX

ruby - 如何使用ruby提取字段

ruby - 查询字符串参数的默认值,Ruby 方式?

ruby - 精简读取已配置的用户环境

ruby-on-rails - MongoDB/Mongoid : Can one query for ObjectID in embedded documents?

ruby-on-rails - 用作哈希键的符号在序列化时转换为字符串

ruby-on-rails - Ruby on Rails 和 MongoDB

mongodb - 使用 MongoDB 按函数嵌套分组

ruby-on-rails - 使用长度标准查询 MongoDB

ruby - MongoDB 驱动程序 ruby​​,删除文档中的字段