gpt4 book ai didi

ruby-on-rails - Ember-data和MongoDB,如何处理_id

转载 作者:行者123 更新时间:2023-12-02 01:54:36 25 4
gpt4 key购买 nike

我正在将 ember-data 与 Rails 和 MongoDB 一起使用,并且在 MongoDB 中将 ID 存储在 _id 字段中时遇到问题。

Ember-data 将使用 id 作为 ID 的默认字段,因此我尝试像这样覆盖它:

App.User = DS.Model.extend
primaryKey: "_id"
name: DS.attr "string"
image: DS.attr "string"

这似乎在大多数情况下都有效,但在某些情况下,我从 ember 中得到异常(exception):

Uncaught Error: assertion failed: Your server returned a hash with the key _id but you have no mappings

我怀疑这可能是 ember-data 中的一个错误,因为它仍在大量开发中,但我试图找到一种方法来将 _id 映射到 Rails 服务器端的 id ?我正在使用 mongoid 进行 mongo 映射。

最佳答案

如果您使用 Mongoid,这里有一个解决方案,使您不必添加方法 def id;对象._id.to_s; end 每个序列化器

添加以下 Rails 初始值设定项

Mongoid 3.x

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

Mongoid 4

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

用于构建的事件模型序列化器

class BuildingSerializer < ActiveModel::Serializer
attributes :id, :name
end

生成的 JSON

{
"buildings": [
{"id":"5338f70741727450f8000000","name":"City Hall"},
{"id":"5338f70741727450f8010000","name":"Firestation"}
]
}

这是 brentkirby 建议的猴子补丁并由 arthurnn 更新为 Mongoid 4

关于ruby-on-rails - Ember-data和MongoDB,如何处理_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571777/

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