Search code examples
ruby-on-railsroutesrails-routingnested-resourcesnested-routes

rails link to nested route not working


I have the following in routes:

resources :projects do
  resources :schedules
end

I am trying to go to the show schedule page. Rake routes lists this:

project_schedule GET  /projects/:project_id/schedules/:id(.:format)  schedules#show

I have the following link on another page to the schedules#show page:

<%= link_to 'Show Schedule', project_schedule_path(project.id, schedule.id) %>

The page returns the following error:

Couldn't find Schedule with id=26

Here are the params:

{"project_id"=>"26",
 "id"=>"48"}

I know a schedule exists with these id's because i can find it in the console:

<Schedule id: 48, project_id: 26, created_at: "2013-11-25 19:08:00", updated_at: "2013-11-25 19:08:00">

Why isn't the link working? Thanks.


Solution

  • Looks like you're trying to find the schedule using the project's id.

    I'd do this in your controller:

    # find the parent model first 
    @project = Project.find params[:project_id]
    
    # now get its associated schedule:
    @schedule = @project.schedules.find params[:id]
    

    You also might have the ids backwards in your link_to helper. You can try using the shortcut:

    link_to 'Schedule', [project, schedule]
    

    That gets converted to the project_schedule_path