Updates are lost on hash field members

289 views
Skip to first unread message

Ehud

unread,
Apr 6, 2011, 6:37:45 AM4/6/11
to Mongoid
Hi all,
I'm trying to use a hash field to store data in a document as follows:
class User
include Mongoid::Document
field :game_stats, :type=>Hash
end

It seems like updates to hash member attributes are not saved to the
database though. Here's the console commands and output I'm getting:
# initialize the user object and create the hash
>> u=User.first
>>u.game_stats["143"] = {"playcount"=>0}
=> {"playcount"=>0}
>> u.game_stats["143"]["playcount"]
=> 0
>> u.save!
=> true

# reload the object and increment playcount
>> u.reload
>> u.game_stats["143"]["playcount"]
=> 0
>> u.game_stats["143"]["playcount"] += 1
=> 1
>> u.save!

# reload the object, playcount was not saved
>> u.reload
>> u.game_stats["143"]["playcount"]
=> 0

There were actually a few times where it did persist, but I couldn't
figure out the pattern.
Am I doing something wrong here? Using the native mongo client works
fine.


Nick Hoffman

unread,
Apr 6, 2011, 1:15:19 PM4/6/11
to mon...@googlegroups.com

Hi Ehud. Which version of Mongoid are you using?

I was able to reproduce the behaviour you showed using 2.0.0.rc.7 . The reason the change to game_stats['147']['playcount'] isn't saved is because Mongoid doesn't consider the document object to have changed. Eg:

 ruby-1.9.2-p0 >   u = User.create! :game_stats => {}
 => #<User _id: 4d9c9f038533c541ce000001, game_stats: {}>
ruby-1.9.2-p0 >  
ruby-1.9.2-p0 >   u.game_stats['147'] = {}
 => {}
ruby-1.9.2-p0 >   u.game_stats['147']['playcount'] = 0
 => 0
ruby-1.9.2-p0 >   u.changes
 => {"game_stats"=>[{}, {"147"=>{"playcount"=>0}}]}
ruby-1.9.2-p0 >
ruby-1.9.2-p0 >   u.save
 => true
ruby-1.9.2-p0 >   u.reload
 => #<User _id: 4d9c9f038533c541ce000001, game_stats: {"147"=>{"playcount"=>0}}>
ruby-1.9.2-p0 >
ruby-1.9.2-p0 >   u.game_stats['147']['playcount'] += 1
 => 1
ruby-1.9.2-p0 >   u.game_stats
 => {"147"=>{"playcount"=>1}}
ruby-1.9.2-p0 >
ruby-1.9.2-p0 >   u.changes
 => {}
ruby-1.9.2-p0 >   u.changed?
 => false
ruby-1.9.2-p0 >   u.save!
 => true
ruby-1.9.2-p0 >   u.reload
 => #<User _id: 4d9c9f038533c541ce000001, game_stats: {"147"=>{"playcount"=>0}}>
ruby-1.9.2-p0 >

Ehud

unread,
Apr 6, 2011, 2:39:55 PM4/6/11
to Mongoid
I'm using mongoid 2.0.0.
Anyway to monkey patch around the issue? Should I open a ticket
somewhere?

Nick Hoffman

unread,
Apr 6, 2011, 4:17:40 PM4/6/11
to mon...@googlegroups.com
On Wednesday, April 6, 2011 2:39:55 PM UTC-4, Ehud wrote:
I'm using mongoid 2.0.0.
Anyway to monkey patch around the issue? Should I open a ticket
somewhere?

It's a bug in my opinion. Open a ticket here, please:
https://github.com/mongoid/mongoid/issues

Take a look at Mongoid's source to see how it keeps track of dirty attributes. You never know...there could be a simple fix for this.

Ehud

unread,
Apr 6, 2011, 4:58:28 PM4/6/11
to Mongoid
Reply all
Reply to author
Forward
0 new messages