How can i set include_root_in_json to false for all my RoR models?
开发者_运维知识库I've tried to set ActiveModel::Base.include_root_in_json = false inside application.rb, but it has no effect.
Model.to_json method is used to returns a JSON string representing the model and i have used self.include_root_in_json = false in a model itself.
But for the whole application you can try setting ActiveModel::Base.include_root_in_json = false in an initializer.[edit This does not work.]
[edit] ActiveRecord::Base.include_root_in_json = true try adding this line to config/environment.rb file.
I'm not sure if this is true for the later versions of rails but for me (running 2.3.5 atm) there was already a declaration for this setting in /config/initializers/new_rails_defaults.rb where it was set to:
ActiveRecord::Base.include_root_in_json = true
So if you try to set this setting in another place then it might be overridden.
On Rails 3.2.2, this is already set in the initializers:
---config/initializers/wrap_parameters.rb
---
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
For default system wide config is alway good idea to set variable in initializers, like config/initializers/defaults.rb
I think you should set ActiveRecord::Base.include_root_in_json = false in config/application.rb
not ActiveModel::Base
At Rails 4 in "config/initializers/wrap_elements.rb" you can uncomment the following:
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = true
end
精彩评论