0

我正在使用带有 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 的顶级行为。默认情况下为真。”

4

4 回答 4

8

我知道这是旧的,但另一种方法是通过将它放在 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
于 2011-02-09T16:54:11.430 回答
4

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

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

  ...
end
于 2010-10-19T21:51:39.507 回答
1
ActiveModel::Base.include_root_in_json = false

在初始化程序中?

于 2010-06-17T05:25:30.597 回答
0

如果你更喜欢初始化器,它ActiveRecord::Base不是ActiveModel::Base在 Rails 版本 2.* 和 3.1 中,可能是 3.0。查看源代码,在 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

于 2011-11-18T09:47:53.287 回答