Shaina33 Shaina33 - 2 years ago 146
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

My UserSerializer:

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

def full_name

Commands in the Rails console:

>> User.create(first_name: "Jane", last_name: "Doe", email: "")

Console returns:

=> {"user"=>{:id=>1, :full_name=>"Jane Doe", :email=>""}}

Answer Source

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: "")

=> "{\"user\":{\"id\":1,\"full_name\":\"Jane Doe\",\"email\":\"\"}}"

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

>> JSON.parse({"user"=>{:id=>1, :full_name=>"Jane Doe", :email=>""}}.to_json)
=> {"user"=>{"id"=>1, "full_name"=>"Jane Doe", "email"=>""}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download