gpt4 book ai didi

ruby-on-rails - 必须 to_json 以字符串形式返回一个 mongoid

转载 作者:行者123 更新时间:2023-12-04 00:19:19 28 4
gpt4 key购买 nike

在我的 Rails API 中,我希望 Mongo 对象作为 JSON 字符串返回,Mongo UID 作为“id”属性而不是“_id”对象。

我希望我的 API 返回以下 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转换 _idid :
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 对象都表现得更明智。

关于ruby-on-rails - 必须 to_json 以字符串形式返回一个 mongoid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23505247/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com