How to set ActiveModel::Base.include_root_in_json to false?
I'm using Rails 3 w/ Mongoid, (so no ActiveRecord). Mongoid uses ActiveModel's "to_json" method, and by default that method includes the root object in the JSON (which I don't want).
I've tried putting this in an initializer:
ActiveModel::Base.include_root_in_json = false
But get the error
uninitialized constant ActiveModel::Base
Any ideas how I can change this? I changed the default directly in the source-code and it worked fine, but obviously I'd like to do it properly.
The variable is defined at the top of this file: Github - activemodel/lib/active_model/serializers/json.rb
From the docs: "The option ActiveModel::B开发者_开发知识库ase.include_root_in_json controls the top-level behavior of to_json. It is true by default."
I know this is old, but another way you can do this is by placing this within your application class in 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
You should simply set it on the class that includes the ActiveModel modules:
class Person
include ActiveModel::Validations
include ActiveModel::Serializers::JSON
self.include_root_in_json = false
...
end
ActiveModel::Base.include_root_in_json = false
in an initializer??
If you prefer initializers, it's ActiveRecord::Base
, not ActiveModel::Base
in Rails versions 2.* and 3.1, possibly 3.0. Looked through the source, and in 3.0 beta it was switched to ActiveModel, but back again to ActiveRecord at some point.
ActiveRecord::Base.include_root_in_json = false
Also, in case you're actually trying to use this functionality, in Rails 3.1 the params wrapper is relevant:
ActionController::ParamsWrapper
Wraps the parameters hash into a nested hash. This will allow clients to submit POST requests without having to specify any root elements.
http://edgeapi.rubyonrails.org/classes/ActionController/ParamsWrapper.html
精彩评论