Question

Could I declare a model with a key called :key, for instance? Is there any word I can't use for a key?

Was it helpful?

Solution

The first question if very easy to answer yourself. Open irb and try:

>> require 'mongo_mapper'
=> true
>> MongoMapper.database = 'test'
=> "test"
>> class Test
>>   include MongoMapper::Document
>>   key :key
>>   end
=> #<MongoMapper::Plugins::Keys::Key:0x101fc7a90 @default_value=nil, @type=nil, @name="key", @options={}>
>> t = Test.new(:key => 'value')
=> #<Test _id: BSON::ObjectID('4c4dcced7123374587000001'), key: "value">
>> t.save
=> true
>> Test.all
=> [#<Test _id: BSON::ObjectID('4c4dcced7123374587000001'), key: "value">]

No errors? I guess key is a valid key!

As far as I know, the only keys you shouldn't use for your own data are _id and _type. You can use either, but they will change behavior. Using _id will make whatever you're setting as that key the unique id for the object. Using _type will cause MongoMapper to try to instantiate an instance of whatever's in your _test key when bringing the object back from the database.

OTHER TIPS

_id and _type. Also, any thing that would create a method the same as a mongomapper doc/edoc instance method, such as associations, etc.

Here's a concrete example of John Nunemaker's answer.

I found out the hard way that the following tokens are referenced in your object's instance code and therefore will collide with any key of the same name (mongo_mapper/plugins/callbacks.b):

:destroy
:save
:create
:update

If you define

key :update, Integer

then you will be able to GET, DELETE, POST, but not PUT because that will try to call run_callbacks(:update), which has become nonsense at that point. I don't know how to fix that so I can have a field called "update" in my model. Anyone?

Follow-up: It seems the instance method that performs the actual update is also called :update, so it would not help to eliminate the use of these tokens for callbacks. Rather, this is just a case of colliding with an instance method that causes a much weirder error because it is used as a callback type FIRST, before being used as a method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top