Last active
July 16, 2017 15:56
-
-
Save spaquet/37448b85ea3ac0b820dec21a330d3caf to your computer and use it in GitHub Desktop.
Basic Rails User Controller & Model (API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UsersController < ApplicationController | |
before_action :set_user, only: [:show, :update, :destroy] | |
# GET /users | |
def index | |
@users = User.all | |
render json: @users | |
end | |
# GET /users/:id | |
def show | |
render json: @user | |
end | |
# POST /users | |
def create | |
@user = User.new(user_params) | |
if @user.save | |
render json: @user, status: :created, location: @user | |
else | |
render json: @user.errors, status: :unprocessable_entity | |
end | |
end | |
# PATCH/PUT /users/1 | |
def update | |
if @user.update(user_params) | |
render json: @user | |
else | |
render json: @user.errors, status: :unprocessable_entity | |
end | |
end | |
# DELETE /users/1 | |
def destroy | |
@user.destroy | |
end | |
private | |
# Use callbacks to share common setup or constraints between actions. | |
def set_user | |
@user = User.find(params[:id]) | |
end | |
# Only allow a trusted parameter "white list" through. | |
def user_params | |
params.require(:user).permit(:email, :password, :password_confirmation) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ApplicationRecord | |
validates :password, length: { minimum: 8 } | |
validates :password, confirmation: true | |
validates :password_confirmation, presence: true | |
validates :email, presence: true, uniqueness: true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment