How can i set include_root_in_json to false for all my RoR models?
Asked Answered
A

6

17

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.

Amice answered 10/12, 2010 at 10:44 Comment(0)
K
12

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.

Knickerbocker answered 10/12, 2010 at 10:44 Comment(3)
this also works for me self.include_root_in_json = false, but ActiveModel::Base.include_root_in_json = false cause an error, like it is not defined. (I'm using Rails 3)Amice
Can you try putting the following line in config/environment.rb ActiveRecord::Base.include_root_in_json = falseKnickerbocker
I've got an initializer in config/initializers/active_record.rb that contains ActiveRecord::Base.include_root_in_json = false and it works fine for me (I'm using Rails 3.0.4). Something you have to remember (it used to catch me out) is if you change an initializer, you need to restart your server or reload your console for it to take effect.Fryer
P
6

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.

Partlet answered 10/12, 2010 at 10:56 Comment(1)
+1 works for me by changing "true" to "false" in config/initializers/new_rails_defaults.rb.Howund
S
2

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
Snare answered 21/9, 2012 at 1:22 Comment(0)
M
1

For default system wide config is alway good idea to set variable in initializers, like config/initializers/defaults.rb

Map answered 10/12, 2010 at 10:50 Comment(0)
M
1

I think you should set ActiveRecord::Base.include_root_in_json = false in config/application.rb

not ActiveModel::Base

Men answered 6/7, 2011 at 7:35 Comment(0)
H
0

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 
Hundredfold answered 14/11, 2015 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.