应该将哪些对象传递给具有三重嵌套路由的link_to?

我应该将哪些对象传递给我的link_to以获得三重嵌套路由? 我想要检索练习秀页面。

show.html.erb – 锻炼

 

的routes.rb

 resources :plans do resources :workouts do resources :exercises end end 

workouts_controller.html.erb

 def show @workout = Workout.find(params[:id]) end 

我尝试了以下方法,但它没有将正确的ID提供给正确的型号。

  

你还必须在show动作中获得@plan

在您的workout_controller.rb中

 def show @plan = Plan.find(params[:plan_id]) @workout = Workout.find(params[:id]) end 

在exercise_controller.rb中

 def show @plan = Plan.find(params[:plan_id]) @workout = Workout.find(params[:workout_id]) @exercise = Exercise.find(params[:id]) end 

你也可以这样做:

 <%= link_to exercise.name, [@plan, @workout, exercise] %> 

建议:尝试获取RailsForZombies 2幻灯片,它有一个很好的部分如何处理嵌套路由,或只是查看指南。

另外,只是为了拥有更清晰的代码,使用回调函数before_filter获取@plan中的workout_controller.rb@plan中的workout_controller.rb@plan

 class WorkoutsController < ApplicationController before_filter :get_plan def get_plan @plan = Plan.find(params[:plan_id]) end def show @workout = Workout.find(params[:id]) end end 

就像托马斯所说,试着避开那些深深嵌套的路线。

如果你正在使用exercise.name我假设你正在通过像@workout.exercises.each do |exercise|的循环@workout.exercises.each do |exercise| , 对?

但是,您必须在控制器中定义@plan。

 def show @plan = Plan.find(params[:plan_id]) @workout = @plan.workouts.find(params[:workout_id]) end 

然后,

 <%= link_to exercise.name, plan_workout_exercise_path(@plan, @workout, exercise) 

避免三重嵌套的一种可能性是构建您的路由,如下所示:

 resources :plans do resources :workouts, except: [:index, :show] end resources :workouts, only: [:index, :show] do resources :exercises end 

你总是可以通过一个级别的嵌套和更容易的链接助手来获得。

 <%= link_to 'Create a new workout', new_plan_workout_path(@plan) %> <%= link_to workout.name, workout_path(@workout) %> <%= link_to 'Create a new exercise', new_workout_exercise_path(@workout) %> <%= link_to exercise.name, workout_exercise_path(@workout, @exercise) %>