Question

I'm reviewing the "Rails Routing From The Outside In" section of the Rails Guides, and I came across this section:

Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like /profile to always show the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action:

get 'profile', to: 'users#show'

Passing a String to match will expect a controller#action format, while passing a Symbol will map directly to an action:

get 'profile', to: :show

The guide says that 'passing a Symbol will map directly to an action', but let's say I have multiple controllers which each have a 'show' action. How does Rails know which one to use, since I'm no longer referencing a specific controller?

Was it helpful?

Solution

That documentation is somewhat misleading, isn't it. It is a poor example. The comment about passing symbols to match is a general comment, and should be outside the section on singular resources.

Indeed if you try it stand-alone, you will get the following error when starting Rails or running rake routes:

rake routes
rake aborted!
missing :controller

So you would have to add a :controller option for that to work outside of a resource declaration:

get 'profile', to: :show, controller: 'users'

The syntax they specify IS valid inside of a resources or resource declaration, e.g.:

resources :user do
  collection do
    get 'profile', to: :show
  end
end

or

resource :user do
  get 'profile', to: :show
end

However both those examples generate different routes from the prior example. So again, I think the comment is misplaced.

OTHER TIPS

It appears that it does not know...

#config/routes.rb

get 'profile', to: :show

From console:

$ rake routes
rake aborted
missing :controller

The first example: 'users#show', does create a successful route, as does

get 'profile', to: :show, controller: 'users'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top