ga-wdi-boston / full-stack-project

Other
8 stars 64 forks source link

display only current users exercises #1018

Closed ryanwk closed 7 years ago

ryanwk commented 7 years ago

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?

cpearce31 commented 7 years ago

Can you post your code from the exercise controller?

ryanwk commented 7 years ago
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
cpearce31 commented 7 years ago

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?

ryanwk commented 7 years ago

that worked!

  # GET /exercises
  def index
    @exercises = current_user.exercises

    render json: @exercises
  end

thank you Caleb