Rails 6.0 routing path name resouces resource etc. are also summarized as a memorandum.
routes.rb
#Routing to access the route
root 'users#show'
root to 'users#show'
root '/', to: 'users#show'
routes.rb
# '/users/:id'Route to the show action of the users controller
get '/users/:id', to: 'users#show'
routes.rb
# 'hoge'Route to show on users controller
# as:You can specify a name for the routing using the option
get '/users/:id', to: 'users#show', as: 'hoge'
When specifying the url with <% = form_with%> <% = link_to%> etc., you can directly specify it like the url such as / posts /: id, but it is not a good idea because there are many corrections when changing. .. Naming with as: makes it easier to modify and the code to read.
resources ... 7 actions are generated with id. Six actions are generated without id, except the resource (singular) ... index action. Resources (multiple) if there are multiple resources in the application such as "photo", "user", "product" If there is only one like "your profile" and you don't need id or index, resource (singular)
routes.rb
resources :photos
With a description like this, the following 7 routes are generated. In this case, both correspond to the Photos controller.
verb | path | controller#action | Purpose |
---|---|---|---|
GET | /photos | photos#index | View a list of all photos |
GET | /photos/new | photos#new | Returns an HTML form to create one photo |
POST | /photos | photos#create | Create one photo |
GET | /photos/:id | photos#show | Show a specific photo |
GET | /photos/:id/edit | photos#edit | Returns one HTML form for photo editing |
PATCH/PUT | /photos/:id | photos#update | Update a specific photo |
DELETE | /photos/:id | photos#destroy | Delete a specific photo |
routes.rb
resource :geocoder
With the above description, the following 6 routes are generated. In this case, both correspond to geocoder.
verb | path | controller#action | Purpose |
---|---|---|---|
GET | /geocoder/new | geocoders#new | Returns an HTML form for geocoder creation |
POST | /geocoder | geocoders#create | Create geocoder |
GET | /geocoder | geocoders#show | Show only one geocoder resource |
GET | /geocoder/edit | geocoders#edit | Returns an HTML form for geocoder editing |
PATCH/PUT | /geocoder | geocoders#update | Update only one geocoder resource |
DELETE | /geocoder | geocoders#destroy | Delete geocoder resource |
Rails routing is performed from the top of the routing file. Therefore, if there are multiple routes with the same condition, only the above route will be valid. If the URL is irrelevant, the order does not matter.
Rails Routing-Rails Guide v6.0 https://railsguides.jp/routing.html
Recommended Posts