Mongoid update_attributes changing data types

Im creating a simple rails utility to modify data in an existing mongo database. I use mongoid for interaction and can just read / destroy objects.

The problem is that my mongo document has a 'node', which is a group of key value pairs that vary by record. When I load a record like this:

MongoObject.find(BSON::ObjectId('ABC1234567890')) => #<MongoObject _id: ABC1234567890, node: {"totallogins"=>11, "id"=>"logIns"}> 

I use the standard rail form to update the values ​​so that the mail data looks like this:

 {"commit"=>"Edit", "utf8"=>"✓", "id"=>"ABC1234567890", "mongo_object"=>{"node"=>{"totallogins"=>"12", "id"=>"logIns"}} 

If i, then do:

 @mongo_object.update_attributes(params[:mongo_object]) 

This works, but changes the data type "totallogins" from int to string, because post data is a string.

Now the active record refers to this very thing, but I need a solution that will work with mongoid.

Any ideas how I can do this?

+4
source share
3 answers

Thanks. Unfortunately, I cannot, because the fields for node are fully dynamic, so I cannot define them. I came up with the following solution, but its a little ugly:

 @mongo_object.node.each do |k,v| new_value = params[:mongo_object][:node][k.to_sym] new_value = new_value.to_i if v.class == Fixnum @mongo_object.node[k] = new_value end @mongo_object.save 
+2
source

If you include node embedded_document, then you can explicitly specify field types when declaring them.

 class Node include Mongoid::Document embedded_in :mongo_object field :totallogins, type: Integer ... end 
0
source

http://mongoid.org/docs/documents/ mentions how to handle types; maybe make sure your type is Integer?

0
source

Source: https://habr.com/ru/post/1341856/