2

I have a class that is not an ActiveRecord object and im trying to create a AM serializer for it. I can return the proper json, but its not including a root

in have this in my controller

format.json { render json: @current_user, root: "current_user" }

and my class looks like this

class CurrentUser 
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :first_name, :last_name, :user_type, :user_id

end

Ive also tried adding this in the controller

 def default_serializer_options
  {root: true}
 end

But still my json object does not have the root which I need for Ember Model

return object

{"first_name":"Luke","last_name":"Skywalker","user_type":"Padawan","user_id":12}

and I need

{current_user: {"first_name":"Luke","last_name":"Skywalker","user_type":"Padawan","user_id":12} }
CoderStash
  • 171
  • 3
  • 15

2 Answers2

5

For anyone in the future who may come across this same problem, when using ActiveModelSerializers 0.10.x, just add to an existing initializer or create a new one and add this to include the root node in your responses:

config/initializers/serializer.rb: ActiveModel::Serializer.config.adapter = :json

AMS documentation states that this is not backwards compatible for versions 0.9.x and 0.8.x.

Graham S.
  • 1,480
  • 1
  • 20
  • 28
1

If using default_serializer_options inside your controller doesn't work, maybe you should have a look into config/initializers/wrap_parameters.rb for include_root_in_json option.

If you are curious, concerned source code for that option can be found here.

Jeremy
  • 167
  • 4