应该将哪些对象传递给具有三重嵌套路由的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) %>
- 具有别名表名的ActiveRecord查询
- 使用Railsvalidation助手:消息,但希望它没有在消息中列出列名
- 无法加载此类文件 – mysql2 / 2.4 / mysql2(LoadError) – windows
- 需要帮助来理解`has_and_belongs_to_many`
- LOAD DATA LOCAL INFILE使用mysql2 gem导致格式错误的数据包错误
- Rails:为什么我的所有scss文件都没有编译?
- Ruby on Rails:如何连接两个表
- time_ago_in_words =>“在{{count}}天内。”?
- time_select form helper将新时间对象解释为UTC而不是配置的时区