add user scaffold
This commit is contained in:
53
app/controllers/users_controller.rb
Normal file
53
app/controllers/users_controller.rb
Normal file
@@ -0,0 +1,53 @@
|
||||
class UsersController < ApplicationController
|
||||
before_action :set_user, only: %i[ show update destroy ]
|
||||
|
||||
# GET /users
|
||||
# GET /users.json
|
||||
def index
|
||||
@users = User.all
|
||||
end
|
||||
|
||||
# GET /users/1
|
||||
# GET /users/1.json
|
||||
def show
|
||||
end
|
||||
|
||||
# POST /users
|
||||
# POST /users.json
|
||||
def create
|
||||
@user = User.new(user_params)
|
||||
|
||||
if @user.save
|
||||
render :show, status: :created, location: @user
|
||||
else
|
||||
render json: @user.errors, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
# PATCH/PUT /users/1
|
||||
# PATCH/PUT /users/1.json
|
||||
def update
|
||||
if @user.update(user_params)
|
||||
render :show, status: :ok, location: @user
|
||||
else
|
||||
render json: @user.errors, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
# DELETE /users/1
|
||||
# DELETE /users/1.json
|
||||
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 list of trusted parameters through.
|
||||
def user_params
|
||||
params.require(:user).permit(:username)
|
||||
end
|
||||
end
|
||||
10
app/models/user.rb
Normal file
10
app/models/user.rb
Normal file
@@ -0,0 +1,10 @@
|
||||
class User < ApplicationRecord
|
||||
validates :username,
|
||||
presence: true,
|
||||
uniqueness: true,
|
||||
length: { maximum: 14 },
|
||||
allow_nil: false,
|
||||
format: {
|
||||
with: /\A[a-zA-Z0-9]+\z/,
|
||||
}
|
||||
end
|
||||
2
app/views/users/_user.json.jbuilder
Normal file
2
app/views/users/_user.json.jbuilder
Normal file
@@ -0,0 +1,2 @@
|
||||
json.extract! user, :id, :username, :created_at, :updated_at
|
||||
json.url user_url(user, format: :json)
|
||||
1
app/views/users/index.json.jbuilder
Normal file
1
app/views/users/index.json.jbuilder
Normal file
@@ -0,0 +1 @@
|
||||
json.array! @users, partial: "users/user", as: :user
|
||||
1
app/views/users/show.json.jbuilder
Normal file
1
app/views/users/show.json.jbuilder
Normal file
@@ -0,0 +1 @@
|
||||
json.partial! "users/user", user: @user
|
||||
Reference in New Issue
Block a user