[RUBY] About Rails routing


We've summarized routing in Rails applications.

This goal

Check the "effect of routing" and "practical usage".

<1> Effect of routing

** Conclusion ** -It will be possible to pass processing to the controller and action based on the HTTP request. -Helper methods allow you to create paths and URIs in controllers and views.

How to specify the controller and action

In routing, HTTP request from client is distributed by the following code.

Routing image

  [HTTP method] '[URI path]', to: '[Controller name]#[Action name]'

Example) get 'samples', to: 'samples#index'

In other words, in this example ...

When the client accesses with ** "GET method" ** and ** "samples path" ** Process with ** "index action" ** of ** "samples controller" ** of Rails application

It means that · · ·

Path and URL helpers will be available in controllers and views

By describing the routing, you can use ** "\ _path method" and "\ _url method" ** in Rails application. This method allows you to write redirect_to methods in controllers, link_to methods in views, etc. using path.

\ _path method ・ \ _url method

It is a helper method that easily generates paths and URLs by using it like ** "[Prefix] \ _ path" ** or ** "[Prefix] \ _ url" **.

<2> Practical usage

Routing setting location

It will be the config / routes.rb file.


  Rails.application.routes.draw do
    get 'samples', to: 'samples#index'

How to check the routing

You can check it by running the command rails routes in the application directory using the terminal.


   (Application directory)$ rails routes

      Prefix    Verb    URI Pattern             Controller#Action
     samples    GET     /samples(.:format)      samples#index

** "Prefix", "Verb", "URI Pattern", "Controller # Action" ** are displayed. Determine the HTTP request content by combining ** "Verb and URI Pattern" ** ** "Controller # Action" ** indicates where to pass the process.

What is Prefix

It is like a variable used when using the "\ _path method" and "\ _url method".

Example) samples_path => "/ samples"     samples_url   =>  " http://sample.com/samples "

What is Verb (HTTP verb)?

It is an HTTP method that determines the processing.

What is URI Pattern?

This is the path of the URI to be processed.

What is Controller # Action?

It will be the controller name and action name to pass the process.

7 basic actions

Rails has ** "7 types of actions" ** that are used as standard.

Action name Intended use
index List
new Show new data form
create Register new data
show Display specific data
edit Display the edit form of specific data
update Update specific data
destroy Delete specific data

How to write basic routing

It can be roughly divided into two. ** "Individual settings" ** and ** "Batch settings" **.

individual setting

This is the code that sets the routing ** line by line **.

  Rails.application.routes.draw do
    get  'samples',     to: 'samples#index'
    post 'samples',     to: 'samples#create'
    put  'samples/:id', to: 'samples#update'

Bulk configuration (resource-based routing)

You can write multiple routing settings in short code.

resources (plural resources)

It is a code that can set the routing of ** 7 actions ** in one line.

  Rails.application.routes.draw do
    resources :samples

Same as the individual configuration routing below

  Rails.application.routes.draw do
    get    'samples',          to: 'samples#index'
    post   'samples',          to: 'samples#create'
    get    'samples/new',      to: 'samples#new',   as: 'new_sample'
    get    'samples/:id/edit', to: 'samples#edit',  as: 'edit_sample'
    get    'samples/:id',      to: 'samples#show',  as: 'sample'
    patch  'samples/:id',      to: 'samples#update'
    put    'samples/:id',      to: 'samples#update'
    delete 'samples/:id',      to: 'samples#destroy'
* As option

By setting ** "as:'XXX'" **, you can specify "XXX" ** in ** Prefix.

resource (singular resource)

It is a code that can set the routing of 6 actions ** other than the ** index action in one line. It is used when ** each user has only one piece of information (resource) in the application design. Since it has only one piece of information, there is no index action (listing multiple resources) ** ": id" ** is not added to the URI path.

Also note that ** controllers are plural **.

  Rails.application.routes.draw do
    resource :sample  #It is singular

Same as the individual configuration routing below

  Rails.application.routes.draw do
    post   'sample',          to: 'samples#create'
    get    'sample/new',      to: 'samples#new',   as: 'new_sample'
    get    'sample/edit',     to: 'samples#edit',  as: 'edit_sample'
    get    'sample',          to: 'samples#show',  as: 'sample'
    patch  'sample',          to: 'samples#update'
    put    'sample',          to: 'samples#update'
    delete 'sample',          to: 'samples#destroy'

How to write advanced routing

Resource-based routing limits

When you want to use some of the resources / resource routing actions ** Specify "only option" ** and ** "except option" **.

  Rails.application.routes.draw do
    #Use only index / show actions
    resources :users, only: [:index, :show]

    #Use other than index / show / edit / update / destroy actions
    resources :books, except: [:index, :show, :edit, :update , :destroy]
   $ rails routes

    Prefix Verb   URI Pattern               Controller#Action
     users GET    /users(.:format)          users#index 
      user GET    /users/:id(.:format)      users#show
     books POST   /books(.:format)          books#create
  new_book GET    /books/new(.:format)      books#new

Add actions for resource-based routing

In addition to the seven basic Rails actions, you can add actions with ** "member routing" ** and ** "collection routing" **.

What is member routing?

This is a routing method that includes ** ": id" ** in the URI path.

member routing

  Rails.application.routes.draw do
    resources :photos do
      member do
        get 'preview'
  $ rails routes

         Prefix Verb   URI Pattern                   Controller#Action
  preview_photo GET    /photos/:id/preview(.:format) photos#preview
         photos GET    /photos(.:format)             photos#index

What is collection routing?

A routing method that does not include the URI path ** ": id" **. The code is written in the same way as member routing.

What changes depending on the presence or absence of ": id" in the URI path

"Id" is the management number of the data registered in the application. The fact that there is an "id" in the path means that "when performing that action, the required data is specified by the control number".

For example, if you explain with 7 basic actions of Rails The ** index / new / create actions ** do not have an "id" in the path. The reason is that ** no specific data ** is needed to display the list, and ** the data to be registered ** does not have an "id".

On the contrary, ** show / edit / update / destroy actions ** ** Because you can view, change, or delete specific registered data ** Without the "id" ** I don't know what data **, so the path contains the "id".

Routing of nested resources

What is nesting

It means "nested". Indicates that the child element is nested inside the parent element in the routing.

Example)Routing of nested resources

  Rails.application.routes.draw do
    resources :books do
      resources :reviews

In this example, the parent element called books has a nested structure with the child element called reviews.

Effect on routing

Nested routing allows you to associate a parent element with the routing of a child element. In the case of the above example, reviews (child elements) are always tied to a specific book (parent element). If you check the routing of reviews (child element), it will look like this.

          Prefix Verb   URI Pattern                                Controller#Action
    book_reviews GET    /books/:book_id/reviews(.:format)          reviews#index
                 POST   /books/:book_id/reviews(.:format)          reviews#create
 new_book_review GET    /books/:book_id/reviews/new(.:format)      reviews#new
edit_book_review GET    /books/:book_id/reviews/:id/edit(.:format) reviews#edit
     book_review GET    /books/:book_id/reviews/:id(.:format)      reviews#show
                 PATCH  /books/:book_id/reviews/:id(.:format)      reviews#update
                 PUT    /books/:book_id/reviews/:id(.:format)      reviews#update
                 DELETE /books/:book_id/reviews/:id(.:format)      reviews#destroy

The ** "Prefix" ** and ** "URI Pattern" ** items have a nesting effect.

Effect on Prefix

The parent element comes before the child element. It is a Prefix that contains parent elements (books) such as book_reviews and new_book_review.

Effect on URI Pattern

The parent element and the id of the parent element are placed before the child element. It will be a URI Pattern containing the parent element (book) / books /: book_id / reviews. The / books /: book_id part is the path that represents a specific parent element "Which parent element the child element is connected to" will be explicitly shown.

That's it.

Recommended Posts

About Rails routing
About Rails 6
Rails Routing Basics
Rails 6.0 Routing Summary
[Rails] About ActiveJob ,!
About Rails controller
About RSpec (Rails)
[Rails] About migration files
[Rails 6] About main gems
Catch Rails Routing Error
[Rails] About active hash
[Rails] devise-related routing summary
About rails application server
About rails kaminari pagination
About rails version specification
MEMO about Rails 6 series
[Rails] About Slim notation
[Note] Rails3 routing confirmation
Understand Rails "shallow" routing
[Rails] Complete routing settings
[rails] About devise defaults
Rails: About partial templates
About rails strong parameters
[Beginner] About Rails Session
About resources that generate RESTful routing for Rails
about the where method (rails)
[Ruby on Rails] about has_secure_password
About naming Rails model methods
[Rails] About scss folder structure
Organize Rails routing using draw
About =
[Rails] About Rspec response test
Rails routing controller view relationship
How to write Rails routing
About Rails scraping method Mechanize
Rails singular resource routing by resource
[Rails] About the Punk List function
About the symbol <%%> in Rails erb
[Rails] About implementation of like function
[Rails] Summary of complicated routing configurations
Set Rails routing other than id
[Rails] About helper method form_with [Basic]
Ruby On Rails devise routing conflict
Consideration about Rails and Clean Architecture
About method.invoke
[Rails g.error]
About Kotlin
Rails basics
About Hinemos
Rails API
Rails migration
About inheritance
[Rails] first_or_initialize
About params
About Docker
rails tutorial
[Ruby on Rails] 1 model CRUD (Routing Main)
About form_for
About Spring ③
[Ruby on Rails] About bundler (for beginners)