我開始使用非SQL數據庫(特別是MongoDB)和Ruby on Rails,因爲我相信靈活的模式將是一個優勢。現在,我很困惑,因爲我期望「只是工作」的一些東西不起作用。具體來說,我的某個網頁上有一個「方法缺失」錯誤。Ruby on Rails和MongoDB模型的未定義方法?
NoMethodError in Users#new
undefined method `email' for #<User _id: BSON::ObjectId('4eb8cbcaef704c02da000017')>
Extracted source (around line #13):
10: <tbody><tr>
11: <td><%= f.label :email %>:</td>
12: <td>
13: <%= f.text_field :email, :placeholder => "your email address" %>
14: </td>
15: </tr>
16: <tr>
在控制檯:
>> User.new.email
NoMethodError: undefined method `email' for #<User _id: BSON::ObjectId('4eb8cc4def704c0358000005')>
from /Library/Ruby/Gems/1.8/gems/activemodel-3.1.1/lib/active_model/attribute_methods.rb:385:in `method_missing'
from (irb):5
該模型是這樣的:(?筆記類用戶不會從任何活動記錄超類繼承......做這件事)
class User
include MongoMapper::Document
attr_accessor :password
attr_accessible :username, :email, :password
email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :username, :presence => true,
:format => { :with => /^[a-zA-Z][a-zA-Z0-9_]+$/ },
:length => { :maximum => 32, :minimum => 4 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence => true,
:length => { :within => 5..32 },
:confirmation => true
(etc...)
很抱歉,但我不能在文檔中找到它。這是否意味着我想擁有的每一個屬性都是關鍵?密鑰索引?例如,我有一個屬性:鹽,不應該索引。 (:密碼不應該被索引......)它們都是密鑰嗎? – Dave
@Dave:'key'只是意思是「屬性」,它與'attr_accessor'類似,但告訴MongoMapper該屬性將被保存在MongoDB集合中;術語很差,因爲「關鍵字」就像關係系統中的「列」或「字段」。索引是使用'ensure_index'完成的。請參閱文檔中的[Keys page](http://mongomapper.com/documentation/plugins/keys.html)和[Indexes page](http://mongomapper.com/documentation/plugins/indexes.html)更多。 –
MongoDB希望它可以運行以及mu太短的大腦可以。 – Trip