Mon*_*key 12 ruby-on-rails mongoid
在我的Rails API中,我希望Mongo对象作为JSON字符串返回,其中Mongo UID是"id"属性而不是"_id"对象.
我希望我的API返回以下JSON:
{
"id": "536268a06d2d7019ba000000",
"created_at": null,
}
Run Code Online (Sandbox Code Playgroud)
代替:
{
"_id": {
"$oid": "536268a06d2d7019ba000000"
},
"created_at": null,
}
Run Code Online (Sandbox Code Playgroud)
我的型号代码是:
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
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 12
你可以猴子补丁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
Run Code Online (Sandbox Code Playgroud)
照顾这些$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
Run Code Online (Sandbox Code Playgroud)
这将使你的所有Mongoid对象都表现得很明智.
对于使用Mongoid 4+的人来说,
module BSON
class ObjectId
alias :to_json :to_s
alias :as_json :to_s
end
end
Run Code Online (Sandbox Code Playgroud)
您可以在as_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
Run Code Online (Sandbox Code Playgroud)
结果:
{
"id": "536268a06d2d7019ba000000",
...
}
Run Code Online (Sandbox Code Playgroud)