2011-05-06 52 views
0

我不明白Mongoid的原子方法推動。Mongoid帶原子的持久性推動

我有這個文件:

class Campaign 
    include Mongoid::Document 

    field :messages, :type => Array # Array of hashes 
end 

現在在控制檯,但消息一齣戲它不堅持。舉個例子:

>> campaign = Campaign.last 
=> #<Campaign _id: 4dc2b6617e296d53f000000d,... 
>> data = {:from => '[email protected]'} 
=> {:from=>"[email protected]"} 
>> campaign.push(:messages, data) 
=> [{:from=>"[email protected]"}] 

日誌現在說:

MONGODB blabla_development['campaigns'].update({"_id"=>BSON::ObjectId('4dc2b6617e296d53f000000d')}, {"$push"=>{:messages=>{:from=>"[email protected]"}}}) 

但是,如果查詢這個文件再次,消息字段是零:

>> campaign = Campaign.last 
=> #<Campaign _id: 4dc2b6617e296d53f000000d,... 
>> campaign.messages 
=> nil 

我如何能堅持這個數據?

謝謝

回答

1

你不是推動一個數組,而是一個散列。啓用安全模式mongoid(mongomapper)如果你想mongodb回答「成功」或「失敗」,而不是「好,無論」。

啓用安全模式,嘗試這種

campaign.safe_mode?(:safe => true) #then carry on. warning, I haven't tested... 

push(... ,:safe => true) #mongomapper 

或更改config

persist_in_safe_mode true 

應該在任何情況下,開發環境如此。

解決您的問題:

#to use array instead of hash, do 
data = ["elem1", "elem2"] 
#or 
campaign.messages << "elem1" 
campaign.messages << "elem2" 
campaign.save!