Skip to content

Instantly share code, notes, and snippets.

@vasilakisfil
Last active November 16, 2015 22:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vasilakisfil/feaf48a69ac0b564c6f3 to your computer and use it in GitHub Desktop.
Save vasilakisfil/feaf48a69ac0b564c6f3 to your computer and use it in GitHub Desktop.
restfull api in rails
class Api::V1::UsersController < Api::V1::BaseController
skip_before_filter :authenticate_user, only: [:create, :resetpassword]
def index
users = policy_scope(User)
render json: users, each_serializer: Api::V1::UserSerializer
end
def resetpassword
user = User.find_by(email: reset_params)
return api_error(status: 404) if user.nil?
if !user.send_reset_password_instructions
return api_error(status: 500)
end
head status: 202
end
def show
user = User.find_by(id: params[:id])
return api_error(status: 404) if user.nil?
authorize user
render json: user, serializer: Api::V1::UserSerializer
end
def create
user = User.new(create_params)
return api_error(status: 422, errors: user.errors) unless user.valid?
user.save!
render(
json: user,
status: 201,
location: api_v1_user_path(user.id),
serializer: Api::V1::UserSerializer
)
end
def update
user = User.find_by(id: params[:id])
return api_error(status: 404) if user.nil?
authorize user
if !user.update_attributes(update_params)
return api_error(status: 422, errors: user.errors)
end
render(
json: user,
status: 200,
location: api_v1_user_path(user.id),
serializer: Api::V1::UserSerializer
)
end
def destroy
user = User.find_by(id: params[:id])
return api_error(status: 404) if user.nil?
authorize user
if !user.destroy
return api_error(status: 500)
end
head status: 204
end
private
def create_params
params.require(:user).permit(
:email, :password, :password_confirmation, :first_name, :last_name
)
end
def update_params
create_params
end
def reset_params
params.require(:user).require(:email)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment