我有一個模型,實體。Mongoid:添加哈希模型,但不能寫入它
class Entity
include Mongoid::Document
field :x
field :y
field :z, type => Hash, :default => {} # new field
end
我向它添加了一個新字段,一個散列。當我嘗試使用它時,出現錯誤。我的代碼是:
e = Entity.first
if e.z["a"] # if there is a key of this in it?
e.z["a"] = e.z["a"] + 1
else
e.z["a"] = 1
end
但是,哈希這個錯誤有一個未定義的方法得到。如果我嘗試爲它創建一個初始化程序,要在現有文檔中設置這些值,則會出現相同錯誤的錯誤。我究竟做錯了什麼?
初始化程序是這樣的:
e = Entity.first
e.write_attribute(:z, {})
感謝
你能發佈錯誤嗎? – 2012-01-14 23:38:53
NoMethodError:undefined方法'get'爲{}:哈希 \t from /Users/wflanagan/sites/marketfu/vendor/bundle/bundler/gems/mongoid-7b3cfd92c5ab/lib/mongoid/field.rb:50:in'get ' \t從/Users/wflanagan/sites/marketfu/vendor/bundle/bundler/gems/mongoid-7b3cfd92c5ab/lib/mongoid/attributes.rb:64:in'read_attribute' \t從/用戶/ wflanagan /網站/ marketfu /vendor/bundle/bundler/gems/mongoid-7b3cfd92c5ab/lib/mongoid/fields.rb:55:in'block in create_accessors' \t from/Users/wflanagan/sites/marketfu/app/models/ – Williamf 2012-01-15 01:22:02