MongoMapper new records contain old record's data
In our Rails app environment (ruby 1.8.7 / rails 2.3.12) I can run the following code:
class MongoTester
include MongoMapper::Document
key :test_arr, Array, :default => []
end
mt = MongoTester.new
mt.test_arr << 24
mt2 = MongoTester.new
The output of mt2.inspect is:
#<MongoTester test_arr: [24], _id: BSON::ObjectId('4e5c089f3beaacad00000002')>
I'm not sure how this is possible. object_id and _id for both records are different. Neither one is saved. We haven't modified MongoMapper in our application (开发者_开发技巧mongomapper 0.8.6). Yet a completely new record contains the data of a previously created different record.
I can't reproduce this in MongoMapper's test suite.
Any information on how this effect is possible or how I can get rid of it would be awesome. Thanks!
That is a bug: file it at https://github.com/jnunemaker/mongomapper/issues/new This bug is fixed in newer versions of MongoMapper
Here's a workaround:
key :test_arr, Array, :default => lambda { [] }
It's because arrays in Ruby are mutable, so your default array object is getting added to each time with <<
. The object_id's of your docs will be different, but the object_id's of the arrays will be the same.
精彩评论