gpt4 book ai didi

ruby-on-rails - Ruby 模型输出 id 作为对象 oid

转载 作者:数据小太阳 更新时间:2023-10-29 06:51:05 25 4
gpt4 key购买 nike

我的 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 的新手,不知道如何继续,所以非常感谢任何帮助

最佳答案

迭代 Kirk 的回答:

在 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

关于ruby-on-rails - Ruby 模型输出 id 作为对象 oid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18646223/

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