如何将ActiveModel :: Base.include_root_in_json设置为false?

Mar*_*k L 0 ruby-on-rails activemodel mongoid ruby-on-rails-3

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

我试过把它放在初始化器中:

ActiveModel::Base.include_root_in_json = false
Run Code Online (Sandbox Code Playgroud)

但得到错误

uninitialized constant ActiveModel::Base
Run Code Online (Sandbox Code Playgroud)

我有什么想法可以改变这个吗?我直接在源代码中更改了默认值并且它工作正常,但显然我想要正确地执行它.

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

从文档:"选项ActiveModel :: Base.include_root_in_json控制to_json的顶级行为.默认情况下是真的."

Ell*_*ler 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
Run Code Online (Sandbox Code Playgroud)