mongoid update_attributes 更改数据类型
我正在创建一个简单的 Rails 应用程序来修改现有 mongo 数据库中的数据。我使用 mongoid 进行交互,并且可以很好地读取/销毁对象。
问题是我的 mongo 文档有一个“节点”,它是一堆键值对,其变化取决于记录。当我像这样加载记录时:
MongoObject.find(BSON::ObjectId('ABC1234567890'))
=> #<MongoObject _id: ABC1234567890, node: {"totallogins"=>11, "id"=>"logIns"}>
我使用标准 Rails 表单来更新值,因此发布数据看起来像:
{"commit"=>"Edit", "utf8"=>"✓", "id"=>"ABC1234567890", "mongo_object"=>{"node"=>{"totallogins"=>"12", "id"=>"logIns"}}
如果我这样做:
@mongo_object.update_attributes(params[:mongo_object])
这可以工作,但会将“totallogins”的数据类型从 int 更改为字符串,因为发布数据是一个字符串。
现在活动记录本身就可以处理这个问题,但我需要一个可以与 mongoid 一起使用的解决方案。
我有什么想法可以做到这一点吗?
Im creating a simple rails app to modify data in an existing mongo database. I'm using mongoid for the interaction and can read/destroy objects just fine.
The problem comes is my mongo document has a 'node' which is a bunch of key value pairs with vary depending on the record. When i load the record like so:
MongoObject.find(BSON::ObjectId('ABC1234567890'))
=> #<MongoObject _id: ABC1234567890, node: {"totallogins"=>11, "id"=>"logIns"}>
I'm using a standard rails form to update the values so the post data looks like:
{"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 datatype of "totallogins" from an int to a string because the post data is a string.
Now active record deals with this itself but i need a solution that will work with mongoid.
Any ideas how i can do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
谢谢。不幸的是我不能,因为节点的字段是完全动态的,所以我无法定义它们。我想出了以下解决方案,但它有点难看:
Thanks. Unfortunately i can't as the fields for node are totally dynamic so i can't define them. I've come up with the following solution but its a tad ugly:
如果将节点设置为嵌入文档,则可以在声明字段时显式设置字段类型。
If you make the node an embedded_document, then you can explicitly set the field types when you declare them.
http://mongoid.org/docs/documents/ 提到了如何处理类型;也许确保您的类型是整数?
http://mongoid.org/docs/documents/ mentions how to deal with types; perhaps make sure your type is an Integer?