Reputation: 189
I don't understand the atomic method push of Mongoid.
I have this document:
class Campaign
include Mongoid::Document
field :messages, :type => Array # Array of hashes
end
And now in the console a play with it but messages it's not persisted. An example:
>> campaign = Campaign.last
=> #<Campaign _id: 4dc2b6617e296d53f000000d,...
>> data = {:from => '[email protected]'}
=> {:from=>"[email protected]"}
>> campaign.push(:messages, data)
=> [{:from=>"[email protected]"}]
The log now says:
MONGODB blabla_development['campaigns'].update({"_id"=>BSON::ObjectId('4dc2b6617e296d53f000000d')}, {"$push"=>{:messages=>{:from=>"[email protected]"}}})
But if a query this document again, the messages field is nil:
>> campaign = Campaign.last
=> #<Campaign _id: 4dc2b6617e296d53f000000d,...
>> campaign.messages
=> nil
How can I persist this data?
Thanks
Upvotes: 0
Views: 1236
Reputation: 40760
You are not pushing an array, but a hash. Enable safe mode mongoid (mongomapper) if you want mongodb to answer "successful" or "failed", instead of "ok, whatever".
to enable safe mode, try this
campaign.safe_mode?(:safe => true) #then carry on. warning, I haven't tested...
push(... ,:safe => true) #mongomapper
or change config
persist_in_safe_mode true
should be true in development environment in any case.
To fix your problem:
#to use array instead of hash, do
data = ["elem1", "elem2"]
#or
campaign.messages << "elem1"
campaign.messages << "elem2"
campaign.save!
Upvotes: 1