Grofit
Grofit

Reputation: 18445

ActiveModel include_root_in_json

I am a bit confused by this option... which can be found in the example below

 user = User.find(1)
  user.as_json
  # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
                  "created_at": "2006/08/01", "awesome": true} }

  ActiveRecord::Base.include_root_in_json = false
  user.as_json
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true}

http://rubydoc.info/gems/activemodel/3.1.3/ActiveModel/Serializers/JSON

Why does ActiveModel require you to use ActiveRecord to tell it that you dont want base objects in the root of your serialized objects?

I cannot seem to get this to work, currently I am doing:

require "active_model"
ActiveRecord::Base.include_root_in_json = false

But it just says that it cannot find the constant "ActiveRecord", which makes sense, but is this just a typo in the docs or is there some real reason for this? as ActiveRecord seems to deal with data storage concerns, ActiveModel seems to deal with augmenting simple models...

Upvotes: 1

Views: 461

Answers (1)

Simon Bagreev
Simon Bagreev

Reputation: 2859

Hmm... Rails source for active model has the same example. Where are you trying to use it? In my ActiveModels I normally do:

class Foo
  include ActiveModel::Serializers::JSON

  # ... more includes

  self.include_root_in_json = false

  # ... model stuff
end

Upvotes: 1

Related Questions