Browse Source

Serialized users

Lou 3 years ago
parent
commit
d0fe04530e

+ 4
- 4
app/controllers/api/v1/users_controller.rb View File

@@ -3,18 +3,18 @@ class Api::V1::UsersController < ApplicationController
3 3
   before_action :check_owner, only: %i[update destroy]
4 4
 
5 5
   def index
6
-    render json: User.all
6
+    render json: UserSerializer.new(User.all).serializable_hash.to_json
7 7
   end
8 8
 
9 9
   def show
10
-    render json: User.find(params[:id])
10
+    render json: UserSerializer.new(@user).serializable_hash.to_json
11 11
   end
12 12
 
13 13
   def create
14 14
     @user = User.new(user_params)
15 15
 
16 16
     if @user.save
17
-      render json: @user, status: :created
17
+      render json: UserSerializer.new(@user).serializable_hash.to_json, status: :created
18 18
     else
19 19
       render json: @user.errors, status: :unprocessable_entity
20 20
     end
@@ -22,7 +22,7 @@ class Api::V1::UsersController < ApplicationController
22 22
 
23 23
   def update
24 24
     if @user.update(user_params)
25
-      render json: @user, status: :ok
25
+      render json: UserSerializer.new(@user).serializable_hash.to_json, status: :ok
26 26
     else
27 27
       render json: @user.errors, status: :unprocessable_entity
28 28
     end

+ 4
- 0
app/serializers/user_serializer.rb View File

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

+ 1
- 1
test/controllers/api/v1/users_controller_test.rb View File

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

Loading…
Cancel
Save