【问题标题】:How to set ActiveModel::Base.include_root_in_json to false?如何将 ActiveModel::Base.include_root_in_json 设置为 false?
【发布时间】:2010-06-17 05:22:54
【问题描述】:

我正在使用带有 Mongoid 的 Rails 3(所以没有 ActiveRecord)。 Mongoid 使用 ActiveModel 的“to_json”方法,默认情况下该方法包含 JSON 中的根对象(我不想要)。

我已尝试将其放入初始化程序中:

ActiveModel::Base.include_root_in_json = false

但得到错误

uninitialized constant ActiveModel::Base

有什么想法可以改变这个吗?我直接在源代码中更改了默认值,它工作正常,但显然我想正确地做到这一点。

变量定义在这个文件的顶部: Github - activemodel/lib/active_model/serializers/json.rb

来自文档: "选项 ActiveModel::Base.include_root_in_json 控制 to_json 的顶层行为,默认为 true。"

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongoid activemodel


    【解决方案1】:

    我知道这是旧的,但另一种方法是将其放在 application.rb 中的应用程序类中:

    # When JSON-encoding a record, don't wrap the attributes in a hash where the
    # key is named after the model
    config.active_record.include_root_in_json = false
    

    【讨论】:

    • 如果您需要将其应用于所有模型的简单方法。
    • 他要的是 ActiveModel,而不是 ActiveRecord,差别很大
    【解决方案2】:

    您应该在包含 ActiveModel 模块的类上简单地设置它:

    class Person
      include ActiveModel::Validations
      include ActiveModel::Serializers::JSON
      self.include_root_in_json = false
    
      ...
    end
    

    【讨论】:

      【解决方案3】:
      ActiveModel::Base.include_root_in_json = false
      

      在初始化器中??

      【讨论】:

      • 啊,你写这个的时候我正在编辑这个问题。我已经尝试过了,但遇到了错误。有什么想法吗?
      • 我已经和更多的人交谈过,并确认这确实是应该这样做的。我的代码中一定有其他东西搞砸了。
      【解决方案4】:

      如果您更喜欢初始化器,它是 ActiveRecord::Base,而不是 Rails 版本 2.* 和 3.1(可能是 3.0)中的 ActiveModel::Base。查看源代码,在 3.0 beta 中它切换到 ActiveModel,但在某个时候又回到 ActiveRecord。

      ActiveRecord::Base.include_root_in_json = false
      

      此外,如果您实际上是在尝试使用此功能,那么在 Rails 3.1 中,参数包装器是相关的:

      ActionController::ParamsWrapper

      将参数散列包装成嵌套散列。这将允许客户端提交 POST 请求而无需指定任何根元素。

      http://edgeapi.rubyonrails.org/classes/ActionController/ParamsWrapper.html

      【讨论】:

        猜你喜欢
        • 2012-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        相关资源
        最近更新 更多