Alexey Zakharov
Alexey Zakharov

Reputation: 25102

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

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.

Upvotes: 17

Views: 7907

Answers (6)

Gregory_ynwa
Gregory_ynwa

Reputation: 168

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 

Upvotes: 0

kpassa615
kpassa615

Reputation: 333

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

Upvotes: 2

Ilake Chang
Ilake Chang

Reputation: 1542

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

not ActiveModel::Base

Upvotes: 1

ranendra
ranendra

Reputation: 2512

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.

Upvotes: 12

DanneManne
DanneManne

Reputation: 21180

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.

Upvotes: 6

Sigurd
Sigurd

Reputation: 7953

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

Upvotes: 1

Related Questions