Closed ryanwk closed 7 years ago
Can you post your code from the exercise controller?
class ExercisesController < ProtectedController
before_action :set_exercise, only: [:show, :update, :destroy]
# GET /exercises
def index
@exercises = Exercise.all
render json: @exercises
end
# GET /exercises/1
def show
render json: @exercise
end
# POST /exercises
def create
@exercise = current_user.exercises.build(exercise_params)
if @exercise.save
render json: @exercise, status: :created, location: @exercise
else
render json: @exercise.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /exercises/1
def update
if @exercise.update(exercise_params)
render json: @exercise
else
render json: @exercise.errors, status: :unprocessable_entity
end
end
# DELETE /exercises/1
def destroy
@exercise.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_exercise
@exercise = current_user.exercises.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def exercise_params
params.require(:exercise).permit( :name, :weight, :user_id)
end
end
Take a look at how the set_exercise
method works:
def set_exercise
@exercise = current_user.exercises.find(params[:id])
end
It uses current_user.exercises
to limit .find
to only look through the currently authenticated users exercises. Maybe you could use a similar approach in your index
action?
that worked!
# GET /exercises
def index
@exercises = current_user.exercises
render json: @exercises
end
thank you Caleb
My 'show all' button displays all exercises, makes sense it's a GET that indexes exercises, so any user when signed in can see other users exercises. That's fine but I'd like to only allow the current user to see only their exercises. I have my controller set up in a way that allows only the current user to change or remove an exercise, which works. So how do I get only the current users exercises to display when they press the 'show all' button?