I have a set of nested routes that look like this:
resources :workouts do
resources :exercises do
resources :reports, shallow: true
end
end
I tried to make them as shallow as possible, but not nesting them simply generated too many errors.
Right now they're working fine except when I try to access the exercises#index
page for a specific workout. I'm linking the page like this:
<%= link_to 'Add/Edit Exercises', workout_exercises_path(@workout, exercise), method: :index %>
And when I click that link I get:
ActiveRecord::RecordNotFound at /workouts/3/exercises
Couldn't find Workout without an ID
The error is called on my exercises_controller
on the indicated line:
class ExercisesController < ApplicationController
before_action :authenticate_user!
def index
@workout = Workout.friendly.find(params[:id]) <<<<<THIS LINE
@exercise = Exercise.new
@exercises = Exercise.all
end
def new
@exercise = Exercise.new
end
def create
@workout = Workout.friendly.find(params[:id])
exercise = @workout.exercises.new(exercise_params)
exercise.user = current_user
if exercise.save
flash[:notice] = "Results saved successfully."
redirect_to [@workout]
else
flash[:alert] = "Results failed to save."
redirect_to [@workout]
end
end
def destroy
@workout = Workout.friendly.find(params[:workout_id])
exercise = @workout.exercises.find(params[:id])
if exercise.destroy
flash[:notice] = "Exercise was deleted successfully."
redirect_to [@workout]
else
flash[:alert] = "Exercise couldn't be deleted. Try again."
redirect_to [@workout]
end
end
private
def exercise_params
params.require(:exercise).permit(:name, :needs_seconds, :needs_weight, :needs_reps, :workout_id)
end
def authorize_user
exercise = Exercise.find(params[:id])
unless current_user == current_user.admin?
flash[:alert] = "You do not have permission to create or delete an exercise."
redirect_to [exercise.workout]
end
end
end
The friendly.find
is because I am using the friendly_id gem, which generates slugs instead of ids in the url. I use it in the same manner in other working models, so I do not believe this is causing the current problem.
Can anyone see why I'm getting this error? I have typed @workout
into the live shell of my error and it says that @workout
is nil
, which means it isn't getting the value somehow. I know this is important information, but don't know how to fix it.