Serialized users

This commit is contained in:
Lou 2021-04-27 17:33:55 +02:00
commit d0fe04530e
3 changed files with 9 additions and 5 deletions

View file

@ -3,18 +3,18 @@ class Api::V1::UsersController < ApplicationController
before_action :check_owner, only: %i[update destroy]
def index
render json: User.all
render json: UserSerializer.new(User.all).serializable_hash.to_json
end
def show
render json: User.find(params[:id])
render json: UserSerializer.new(@user).serializable_hash.to_json
end
def create
@user = User.new(user_params)
if @user.save
render json: @user, status: :created
render json: UserSerializer.new(@user).serializable_hash.to_json, status: :created
else
render json: @user.errors, status: :unprocessable_entity
end
@ -22,7 +22,7 @@ class Api::V1::UsersController < ApplicationController
def update
if @user.update(user_params)
render json: @user, status: :ok
render json: UserSerializer.new(@user).serializable_hash.to_json, status: :ok
else
render json: @user.errors, status: :unprocessable_entity
end

View file

@ -0,0 +1,4 @@
class UserSerializer
include JSONAPI::Serializer
attributes :email, :username
end

View file

@ -11,7 +11,7 @@ class Api::V1::UsersControllerTest < ActionDispatch::IntegrationTest
assert_response :success
# Test to ensure response contains the correct email
json_response = JSON.parse(self.response.body)
assert_equal @user.email, json_response['email']
assert_equal @user.email, json_response['data']['attributes']['email']
end
#CREATE