Shaina33 Shaina33 - 6 months ago 62
JSON Question

ActiveModel::Serializer not returning valid JSON in rails console test

I'm relatively new to Rails, and this is my first usage of ActiveModel:Serializer. I'm just trying to set up a simple serializer and test it in the rails console before continuing. It seems to be using the serializer, but not returning valid JSON format. From the instructions I'm working off of (I'm a student), it seems I should be receiving JSON. I've been researching for the past few hours, but everything seems unrelated or goes over my head.

My User model:

class User < ActiveRecord::Base
# User has attributes: first_name, last_name, email, password
has_many :lists

def full_name
first_name + " " + last_name
end
end


My UserSerializer:

class UserSerializer < ActiveModel::Serializer
attributes :id, :full_name, :email

def full_name
object.full_name
end
end


Commands in the Rails console:

>> User.create(first_name: "Jane", last_name: "Doe", email: "test@fake.com")
>> UserSerializer.new(User.first).as_json


Console returns:

=> {"user"=>{:id=>1, :full_name=>"Jane Doe", :email=>"test@fake.com"}}

Answer

as_json constructs a Ruby Hash that can subsequently be "serialized" (converted to a string) by a serialization library.

Try calling to_json instead. This method will return a string that can be parsed.

>> User.create(first_name: "Jane", last_name: "Doe", email: "test@fake.com")
>> UserSerializer.new(User.first).to_json

=> "{\"user\":{\"id\":1,\"full_name\":\"Jane Doe\",\"email\":\"test@fake.com\"}}"

Use JSON.parse to deserialize the string back to a hash:

>> JSON.parse({"user"=>{:id=>1, :full_name=>"Jane Doe", :email=>"test@fake.com"}}.to_json)
=> {"user"=>{"id"=>1, "full_name"=>"Jane Doe", "email"=>"test@fake.com"}}