代码之家  ›  专栏  ›  技术社区  ›  Mark L

如何将activeModel::base.include_root_in_json设置为false?

  •  0
  • Mark L  · 技术社区  · 14 年前

    我使用的是带有MongoID的Rails3(所以没有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的顶级行为。默认情况下是真的。”

    4 回复  |  直到 13 年前
        1
  •  1
  •   Cody Caughlan    14 年前
    ActiveModel::Base.include_root_in_json = false
    

    在初始值设定项中??

        2
  •  8
  •   Elliot Winkler    13 年前

    我知道这很古老,但另一种方法是将其放在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
    
        3
  •  4
  •   neonski    14 年前

    您只需在包含ActiveModel模块的类上设置它:

    class Person
      include ActiveModel::Validations
      include ActiveModel::Serializers::JSON
      self.include_root_in_json = false
    
      ...
    end
    
        4
  •  0
  •   Woahdae    13 年前

    如果你喜欢初始值设定项,它是 ActiveRecord::Base 不是 ActiveModel::Base 在Rails版本2.*和3.1中,可能是3.0。查看源代码,在3.0测试版中,它被切换到ActiveModel,但在某个时刻又回到ActiveRecord。

    ActiveRecord::Base.include_root_in_json = false
    

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

    操作控制器::paramswrapper

    将参数哈希包装为嵌套哈希。这将允许客户端提交POST请求,而不必指定任何根元素。

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