1

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...

Grofit
  • 17,693
  • 24
  • 96
  • 176

1 Answers1

1

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
Simon Bagreev
  • 2,879
  • 1
  • 23
  • 24
  • I didn't think you could set it per model, as there was a question around that somewhere on stackoverflow. I am currently using the ActiveModel::Serializers::JSON like you are within my model, and setting the include_root_in_json at root level within the boot.rb as *apparently* you can only set it for all or nothing. – Grofit Dec 07 '11 at 09:51