Ruby模型输出id作为对象oid

azz*_*z0r 8 ruby ruby-on-rails mongoid backbone.js

我的红宝石模型,如下:

class User
  include Mongoid::Document
  field :first_name, type: String
  field :birthdate, type: Date

  validates :first_name, :birthdate, :presence => true

end
Run Code Online (Sandbox Code Playgroud)

输出一个像这样的对象:

{
_id: {
$oid: "522884c6c4b4ae5c76000001"
},
birthdate: null,
first_name: null,
}
Run Code Online (Sandbox Code Playgroud)

我的骨干项目不知道如何处理_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
Run Code Online (Sandbox Code Playgroud)

I have no idea where to put this, and how to invoke it on the model output, so I tried inside:

/config/initializers/secret_token.rb

I'm new to Ruby and Rails and have no idea how to proceed, so any help is greatly appreciated

Gre*_*sov 29

迭代柯克的回答:

在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
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用:如果你按照前面的答案中的指定添加`alias:to_json:to_s`解决方案,你将收到以下错误:`ArgumentError:错误的参数个数(1表示0) (2认同)

Art*_*ves 6

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

/config/initializers/mongoid.rb

module Moped
  module BSON
    class ObjectId
      alias :to_json :to_s
      alias :as_json :to_s
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


Ron*_*ain 4

对于使用 Mongoid 4+ 的人使用这个,

module BSON
  class ObjectId
    alias :to_json :to_s
    alias :as_json :to_s
  end
end
Run Code Online (Sandbox Code Playgroud)

参考