让to_json返回一个mongoid作为字符串 [英] Have to_json return a mongoid as a string
本文介绍了让to_json返回一个mongoid作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Rails API中,我希望Mongo对象以JSON字符串的形式返回,而Mongo UID作为"id"属性而不是"_id"对象.
In my Rails API, I'd like a Mongo object to return as a JSON string with the Mongo UID as an "id" property rather than as an "_id" object.
我希望我的API返回以下JSON:
I want my API to return the following JSON:
{
"id": "536268a06d2d7019ba000000",
"created_at": null,
}
代替:
{
"_id": {
"$oid": "536268a06d2d7019ba000000"
},
"created_at": null,
}
我的模型代码是:
class Profile
include Mongoid::Document
field :name, type: String
def to_json(options={})
#what to do here?
# options[:except] ||= :_id #%w(_id)
super(options)
end
end
推荐答案
您可以猴子补丁Moped::BSON::ObjectId
:
module Moped
module BSON
class ObjectId
def to_json(*)
to_s.to_json
end
def as_json(*)
to_s.as_json
end
end
end
end
处理$oid
内容,然后Mongoid::Document
将_id
转换为id
:
to take care of the $oid
stuff and then Mongoid::Document
to convert _id
to id
:
module Mongoid
module Document
def serializable_hash(options = nil)
h = super(options)
h['id'] = h.delete('_id') if(h.has_key?('_id'))
h
end
end
end
这将使您所有的Mongoid对象表现出合理的行为.
That will make all of your Mongoid objects behave sensibly.
这篇关于让to_json返回一个mongoid作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文