12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- class Api::V1::UsersController < ApplicationController
- before_action :set_user, only: %i[show update destroy]
- before_action :check_owner, only: %i[update destroy]
-
- def index
- render json: UserSerializer.new(User.all).serializable_hash.to_json
- end
-
- def show
- if params[:included] === "true"
- options = { include: [:activities] }
- render json: UserSerializer.new(@user, options).serializable_hash.to_json
- else
- render json: UserSerializer.new(@user).serializable_hash.to_json
- end
- end
-
- def create
- @user = User.new(user_params)
-
- if @user.save
- render json: UserSerializer.new(@user).serializable_hash.to_json, status: :created
- else
- render json: @user.errors, status: :unprocessable_entity
- end
- end
-
- def update
- if @user.update(user_params)
- render json: UserSerializer.new(@user).serializable_hash.to_json, status: :ok
- else
- render json: @user.errors, status: :unprocessable_entity
- end
- end
-
- def destroy
- @user.destroy
- head 204
- end
-
- private
-
- # Only allow a trusted parameter "white list" through.
- def user_params
- params.require(:user).permit(:email, :username, :password)
- end
-
- def set_user
- @user = User.find(params[:id])
- end
-
- def check_owner
- head :forbidden unless @user.id == current_user&.id
- end
- end
|