简体   繁体   中英

How does Rails know which controller's “show” action to use in this example from Rails Guides?

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?

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'

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, eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM