【问题标题】:Rails 3.1 include_root_in_jsonRails 3.1 包含_root_in_json
【发布时间】:2011-06-29 03:25:51
【问题描述】:

ActiveRecord::Base.include_root_in_json = true 似乎无法在 rails 3.10.rc4 中运行,我在文档中也没有看到。

由于根元素现在默认关闭,我们如何重新启用它?

rails 3.1 中的@comments.to_json 现在看起来像

[
  {
    comment: "Fun street park.",
    created_at: 2011-06-29T02:28:29Z,
  }
]

在以前的版本中,它有我需要返回的根节点。

[
  {
    comment: {
      comment: "Fun street park.",
      created_at: 2011-06-29T02:28:29Z
    }
  }
]

【问题讨论】:

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


    【解决方案1】:

    事实证明,Rails 3.1 只是为您创建了这个 json 配置文件。我不知道这个文件在这里,所以我在初始化程序中的文件被忽略了。

    在上面 Ryan 的回答中确实覆盖了这个设置。

    config/initializers/wrap_parameters.rb

    # Be sure to restart your server when you modify this file.
    #
    # This file contains settings for ActionController::ParamsWrapper which
    # is enabled by default.
    
    # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
    ActionController::Base.wrap_parameters :format => [:json]
    
    # Disable root element in JSON by default.
    if defined?(ActiveRecord)
      ActiveRecord::Base.include_root_in_json = false
    end
    

    【讨论】:

      【解决方案2】:

      尝试直接在您的 Comment 模型上进行设置。

      class Comment < ActiveRecord::Base
        self.include_root_in_json = true
      end
      

      【讨论】:

        【解决方案3】:

        此外,rails 3.1 中新增的 params 包装器也很有趣:

        ActionController::ParamsWrapper

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

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

        【讨论】:

          猜你喜欢
          • 2011-11-24
          • 1970-01-01
          • 2011-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多