You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
correction-tp-rails/app/controllers/creatures_controller.rb

41 lines
1.0 KiB

class CreaturesController < ApplicationController
SHOWABLE_ATTRIBUTES = [:id, :name, :health_points]
def index
@creatures = Creature.all
render json: @creatures.as_json(only: SHOWABLE_ATTRIBUTES)
end
def show
@creature = Creature.find(params[:id])
render json: @creature.as_json(only: SHOWABLE_ATTRIBUTES)
rescue ActiveRecord::RecordNotFound
render json: {}, status: 404
end
def create
@creature = Creature.new(create_or_update_params)
@creature.health_points = rand(3..30)
@creature.save!
render json: @creature.as_json(only: SHOWABLE_ATTRIBUTES)
end
def update
@creature = Creature.alive.find(params[:id])
@creature.update!(create_or_update_params)
render json: @creature.as_json(only: SHOWABLE_ATTRIBUTES)
rescue ActiveRecord::RecordNotFound
render json: {}, status: 404
end
def destroy
@creature = Creature.find(params[:id])
@creature.destroy!
head :no_content
end
private
def create_or_update_params
params.require(:creature).permit(:name)
end
end