Ruby on rails 必须将mongoid作为字符串返回
在我的Rails API中,我希望Mongo对象以JSON字符串的形式返回,Mongo UID作为“id”属性,而不是作为“\u id”对象 我希望API返回以下JSON:Ruby on rails 必须将mongoid作为字符串返回,ruby-on-rails,mongoid,Ruby On Rails,Mongoid,在我的Rails API中,我希望Mongo对象以JSON字符串的形式返回,Mongo UID作为“id”属性,而不是作为“\u id”对象 我希望API返回以下JSON: { "id": "536268a06d2d7019ba000000", "created_at": null, } 而不是: { "_id": { "$oid": "536268a06d2d7019ba000000" }, "created_at": null, }
{
"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
您可以将
中的数据更改为_json
方法,而数据为哈希:
class Profile
include Mongoid::Document
field :name, type: String
def as_json(*args)
res = super
res["id"] = res.delete("_id").to_s
res
end
end
p = Profile.new
p.to_json
结果:
{
"id": "536268a06d2d7019ba000000",
...
}
您可以使用monkey patch
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
将\u id
转换为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对象行为合理。例如:
user = collection.find_one(...)
user['_id'] = user['_id'].to_s
user.to_json
本报税表
{
"_id": "54ed1e9896188813b0000001"
}
对于使用Mongoid 4+的人,请使用此
module BSON
class ObjectId
alias :to_json :to_s
alias :as_json :to_s
end
end
课程简介
include Mongoid::Document
字段:名称,类型:字符串
def to_json
as_json(除了::_id).merge(id:id.to_s).to_json
结束
结束
如果不想更改MongoId的默认行为,只需将结果转换为json即可
profile.as_json.map{k,v|[k,v.is_a?(BSON::ObjectId)?v.to_s:v]}.to_h
另外,这个转换其他的
BSON::ObjectId
像user\u id
我假设第一个块允许正确保存返回的对象,尽管有第二个块。@zishe第一个块给你“536268a06d2d7019ba000000”
而不是{“$oid”:“536268a06d2d7019ba000000”
,第二个块代替“id”
和JSON中的“id”
。我得到了:)我只是想指出一个事实,如果某个api带有前端部分,它可以修改这个对象,然后发送请求保存它,它将无法工作。它主要是以@MonkeyBonkey作为警告,而不是以en-error作为解决方案。@zishe如果您遵循通常的模式:m=Model.find(id);m、 更新属性(…)
。还是我遗漏了什么?我不是想挑起一场争斗,我真的很好奇我是否错过了什么,或者是否有什么事情不够清楚。是的,也许你是对的。我做了同样的事情,所以我想说得更准确一些。请不要。我刚刚花了2个小时调试了一些非常奇怪的行为,结果证明这段代码(复制/粘贴到代码库中)是罪魁祸首to_s
不像_json那样接受可选参数@穆太短了,他的回答说明了这一点。此外,重写该方法至少会在stacktrace中显示monkey补丁。从原始方法中分离出来的别名将更难找到。很好,不需要修补,并且对于特定的模型非常清晰。