Ruby模型输出id作为对象oid

我的ruby模型,如下:

class User include Mongoid::Document field :first_name, type: String field :birthdate, type: Date validates :first_name, :birthdate, :presence => true end 

输出一个像这样的对象:

 { _id: { $oid: "522884c6c4b4ae5c76000001" }, birthdate: null, first_name: null, } 

我的骨干项目不知道如何处理_id。$ oid。

我发现这篇文章和代码:

https://github.com/rails-api/active_model_serializers/pull/355/files

 module Moped module BSON class ObjectId alias :to_json :to_s end end end 

我不知道在哪里放这个,以及如何在模型输出上调用它,所以我尝试了内部:

/config/initializers/secret_token.rb

我是Ruby和Rails的新手,不知道如何继续,所以非常感谢任何帮助

你应该做的是将它放在初始化文件夹中,创建一个这样的文件:

/config/initializers/mongoid.rb

 module Moped module BSON class ObjectId alias :to_json :to_s alias :as_json :to_s end end end 

迭代柯克的回答:

在Mongoid 4中,Moped的BSON实现已被删除,有利于MongoDB bson gem,因此Mongoid 4用户的正确版本是:

 module BSON class ObjectId def to_json(*args) to_s.to_json end def as_json(*args) to_s.as_json end end end 

Aurthur的答案适用于除rabl之外的所有事情。 如果您使用rabl属性:id将抛出exception。 以下代码将与rabl兼容。

 module Moped module BSON class ObjectId def to_json(*args) to_s.to_json end def as_json(*args) to_s.as_json end end end end 

有关更多信息,请参阅github问题https://github.com/nesquena/rabl/issues/337

对于使用Mongoid 4+的人来说,

 module BSON class ObjectId alias :to_json :to_s alias :as_json :to_s end end 

参考

这是一个更好的答案

 require "bson" class Jbuilder < JbuilderProxy def _extract_method_values(object, *attributes) attributes.each do |key| value = object.public_send(key) if value.is_a? ::BSON::ObjectId value = value.to_s end _set_value key, value end end end