ruby-on-rails – 让to_json返回一个mongoid作为一个字符串
发布时间:2020-12-16 22:32:28 所属栏目:百科 来源:网络整理
导读:在我的Rails API中,我希望Mongo对象作为 JSON字符串返回,Mongo UID作为“id”属性而不是“_id”对象. 我希望我的API返回以下JSON: { "id": "536268a06d2d7019ba000000","created_at": null,} 代替: { "_id": { "$oid": "536268a06d2d7019ba000000" },} 我
在我的Rails API中,我希望Mongo对象作为
JSON字符串返回,Mongo UID作为“id”属性而不是“_id”对象.
我希望我的API返回以下JSON: { "id": "536268a06d2d7019ba000000","created_at": null,} 代替: { "_id": { "$oid": "536268a06d2d7019ba000000" },} 我的型号是: 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: 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对象行为明智. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |