我有一组嵌套路线,如下所示:
resources :workouts do
resources :exercises do
resources :reports, shallow: true
end
end
我试图让它们尽可能浅,但是没有嵌套它们只会产生太多错误。
现在他们工作正常,除非我尝试访问特定锻炼的exercises#index
页面。我是这样链接页面的:
<%= link_to 'Add/Edit Exercises', workout_exercises_path(@workout, exercise), method: :index %>
当我点击该链接时,我得到了:
ActiveRecord::RecordNotFound at /workouts/3/exercises
Couldn't find Workout without an ID
在指定行的exercises_controller
上调用错误:
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
friendly.find
是因为我正在使用friendly_id gem,它会在url中生成slugs而不是id。我在其他工作模型中以相同的方式使用它,所以我不相信这会导致当前的问题。
任何人都可以看到为什么我收到此错误?我在错误的实时shell中输入了@workout
,并且@workout
是nil
,这意味着它无法以某种方式获取值。我知道这是重要的信息,但不知道如何解决它。
答案 0 :(得分:0)
问题是:
您的路线为/workouts/3/exercises
,因此格式如下:/workouts/:workout_id/exercises
所以只需稍微修改一下create
方法:
def create
@workout = Workout.friendly.find(params[:workout_id])
exercise = @workout.exercises.build(exercise_params)
...
end
答案 1 :(得分:0)
def index
@workout = Workout.friendly.find(params[:workout_id])
@exercise = Exercise.new
@exercises = Exercise.all
end
试试这个,希望这会对你有帮助。