【问题标题】:Key for mongoid model doesn't workmongoid 模型的键不起作用
【发布时间】:2012-10-22 18:08:17
【问题描述】:

我将 gem mongoid 安装到 RoR 应用程序,但收到错误“未定义的方法 `key?' for nil:NilClass" 同时将属性分配给键功能。

所以我有这个模型:

 class Author
      include Mongoid::Document
      field :name
      key :name
    end

默认脚手架控制器并运行此 url localhost:3000/authors ,收到此错误

NoMethodError in AuthorsController#index

undefined method `key?' for nil:NilClass
Rails.root: C:/Users/Jeremy/RubymineProjects/university

宝石文件:

source 'https://rubygems.org'

gem 'rails', '3.2.6'
gem "mongoid", "~> 3.0.0"
gem "bson_ext", "~> 1.2"

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

我使用了来自这里的指南http://railscasts.com/episodes/238-mongoid?view=asciicast,两次都做了同样的事情。

【问题讨论】:

  • 你运行过 rake db:migrate 吗?

标签: ruby-on-rails mongodb mongoid


【解决方案1】:

Model.identity 和 Model.key 已被删除。对于自定义 ID,用户 现在必须覆盖 _id 字段。当默认值为 proc 时, 设置所有其他属性后应用默认值。

class Band
  include Mongoid::Document
  field :_id, type: String, default: ->{ name } # which was `key :name` before v3
end

文档:http://mongoid.org/en/mongoid/docs/upgrading.html

【讨论】:

    【解决方案2】:

    Mongoid 在版本 3 中发生了很大变化。(asciicast 想要gem 'mongoid', '2.0.0.beta.19'...)

    http://mongoid.org/en/mongoid/index.html查看 mongoid 文档

    最后,Mongoid 3似乎不支持自定义和复合键字段

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 2011-06-15
      相关资源
      最近更新 更多