Ruby 模型输出 ID 作为对象 oid [英] Ruby model output id as object oid

查看:23
本文介绍了Ruby 模型输出 ID 作为对象 oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 ruby​​ 模型,如下所示:

My ruby model, like so:

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.

My backbone project has no idea how to handle _id.$oid.

我找到了这篇文章和代码:

I found this article and code:

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

我不知道把它放在哪里,以及如何在模型输出上调用它,所以我在里面尝试:

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

/config/initializers/secret_token.rb

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

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

推荐答案

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

For guys using Mongoid 4+ use this,

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

参考

这篇关于Ruby 模型输出 ID 作为对象 oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆