Search code examples
ruby-on-railsshowruby-on-rails-5rails-routinglink-to

How do I get my link_to to go to my show method?


I’m using Rails 5. I’m having trouble linking to a show method in my controller. I have this defined in my config/routes

  resources :scenarios do
    resources :confidential_memos
  end

and in a view, I put this

<td><%= link_to "#{subscription.scenario.title}", scenarios_path(subscription.scenario) %>

in my controller I have the show method

class ScenariosController < ApplicationController

  def show
    @scenario = Scenario.find(params[:id])
  end

but when I click on the link, I get the error

The action 'index' could not be found for ScenariosController

How do I get my link to get to my show action?


Solution

  • scenarios_path uses the plural "scenarios" so it is looking for several scenarios and that maps to the index action, hence your error. To show a single scenario you'd use the singular:

    scenario_path(subscription.scenario)
    

    If you only have a show action then you might want to be explicit in your routes:

    resources :scenarios, :only => %i[ show ] do
      #...
    end
    

    so that you catch the error sooner.

    You could solve this yourself by doing a rake routes and looking for the show action that you're interested in.