ActiveModel include_root_in_json

发布于 2024-12-19 15:44:28 字数 881 浏览 1 评论 0原文

我对这个选项有点困惑......可以在下面的示例中找到

 user = User.find(1)
  user.as_json
  # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
                  "created_at": "2006/08/01", "awesome": true} }

  ActiveRecord::Base.include_root_in_json = false
  user.as_json
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true}

http://rubydoc.info/gems/activemodel/3.1.3/ActiveModel/Serializers/JSON

为什么 ActiveModel 要求您使用 ActiveRecord 告诉它您不希望在序列化对象的根?

我似乎无法让它工作,目前我正在做:

require "active_model"
ActiveRecord::Base.include_root_in_json = false

但它只是说它找不到常量“ActiveRecord”,这是有道理的,但这只是文档中的错字还是有真正的原因?由于 ActiveRecord 似乎处理数据存储问题,ActiveModel 似乎处理增强简单模型......

I am a bit confused by this option... which can be found in the example below

 user = User.find(1)
  user.as_json
  # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
                  "created_at": "2006/08/01", "awesome": true} }

  ActiveRecord::Base.include_root_in_json = false
  user.as_json
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true}

http://rubydoc.info/gems/activemodel/3.1.3/ActiveModel/Serializers/JSON

Why does ActiveModel require you to use ActiveRecord to tell it that you dont want base objects in the root of your serialized objects?

I cannot seem to get this to work, currently I am doing:

require "active_model"
ActiveRecord::Base.include_root_in_json = false

But it just says that it cannot find the constant "ActiveRecord", which makes sense, but is this just a typo in the docs or is there some real reason for this? as ActiveRecord seems to deal with data storage concerns, ActiveModel seems to deal with augmenting simple models...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-黛色若梦 2024-12-26 15:44:28

嗯... 活动模型的 Rails 源 有相同的示例。
你想在哪里使用它?在我的 ActiveModels 中,我通常这样做:

class Foo
  include ActiveModel::Serializers::JSON

  # ... more includes

  self.include_root_in_json = false

  # ... model stuff
end

Hmm... Rails source for active model has the same example.
Where are you trying to use it? In my ActiveModels I normally do:

class Foo
  include ActiveModel::Serializers::JSON

  # ... more includes

  self.include_root_in_json = false

  # ... model stuff
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文