Search code examples
ruby-on-railsrouteslink-tonested-routes

What objects should be passed to a link_to with triple nested route?


What objects should I pass to my link_to for a triple nested route? I want to retrieve the exercise show page.

show.html.erb - workouts

<%= link_to exercise.name, plan_workout_exercise_path(???) %>

routes.rb

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

workouts_controller.html.erb

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

I have attempted the following, but it doesn't feed the right ID to the right model.

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

Solution

  • You also have to get @plan in the show action:

    In your workout_controller.rb:

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

    In your exercise_controller.rb:

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

    Also you can do it like this:

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

    Recommendation: Try to get RailsForZombies 2 slides, it has a nice section how to deal with nested routes, or just look at the guides.

    Also, just for the sake of having cleaner code, get the @plan in the workout_controller.rb and @plan and @workout in the exercise_controller.rb with a callback function before_filter:

    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
    

    And like Thomas said, try avoiding those deeply nested routes.