Reputation: 49
From Hartl's Rails Tutorial Book, some routes for static pages are automatically generated:
Rails.application.routes.draw do
get 'static_pages/home'
get 'static_pages/help'
root 'application#hello'
end
Why do the 'home' and 'help' routes not have the controller#action?
E.g. get 'static_pages/home', to: 'static_pages_controller#home'
The closest documentation of this I could find was in the the Rails Guides routing page's static segments section.
Upvotes: 0
Views: 464
Reputation: 1873
After browsing through some documentation, and finding nothing relevant, I had a look at the source. It seems that the match
method (which get
is a shorthand for) is calling get_to_from_path
(defined here), which extracts the controller and method information from the provided path
, if to:
isn't provided.
So, for this scenario, this
get 'static_pages/home'
get 'static_pages/help'
gets mapped to static_pages#home
, and static_pages#help
. Using dashes (-
) instead of underscores (_
) in the path would work as well.
It is weird that this functionality is not documented, and more so that it is used in a tutorial without explanation.
Upvotes: 0
Reputation: 1733
The routes
get 'static_pages/home'
get 'static_pages/help'
do not have a controller/action associated with them because the contents of those pages are not generated dynamically from the controller. They are most likely defined on the file system at public/static_pages/home
and public/static_pages/help
. The public directory can be used to serve static content directly without using controllers.
Edit:
If static_pages does refer to a controller then most likely Rails is able to derive the name of the controller and the name of the action when you create a route of the form <name of controller>/<name of action
. Rails just assumes that the left hand side of the "/" is the controller and the right hand side is the action.
Upvotes: 0