[Ruby] About Rails routing

5 minute read

Overview

I have summarized routing in a Rails application.

This time goal

It is to confirm “effect of routing” and “practical use”.

<1> Routing effect

Conclusion ・Process can be passed to controller and action based on HTTP request.

  • Helper methods allow controllers and views to create paths and URIs.

How to specify controller and action

In the routing, the HTTP request from the client is distributed with 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 access is made from the client with “GET method” and “samples path” It is processed by index action” of **“samples controller” of Rails application.

It means that · · ·

Paths and URL helpers can be used in controllers and views

By describing the route, you can use ** “_path method” / “_url method” ** in the Rails application. This method enables you to write redirect_to method in controller, link_to method in view, etc. using path.

_path method ・_url method

It is a helper method that can easily generate a path or URL by using it like “[Prefix]_path”** or [[Prefix]_url”.

  • Prefix will be explained later.

<2> Practical usage

Where to set the routing

This is the config/routes.rb file.

config/routes.rb


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

How to check routing

You can check this by using the terminal and running the command rails routes in your application’s directory.

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. Judging the HTTP request content by combining “Verb and URI Pattern” “Controller#Action” indicates the destination to which the process is passed.

What is Prefix

It is like a variable used when using “_path method” and “_url method”.

Example) samples_path => “/samples “ Sample_url => “http://sample.com/samples”

What is Verb (HTTP verb)

It is an HTTP method that determines processing.

What is ### URI Pattern It will be the path of the URI for processing judgment.

Controller#Action

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

7 basic actions

Rails has a standard set of “7 types of actions”**.

Action name Purpose of use
index Show list
new Display a new data form
create Register new data
show Show specific data
edit Show edit form for specific data
update Updates specific data
destroy Delete specific data

Basic routing description method

It can be roughly divided into two. “Individual setting” and “Batch setting”.

individual setting

It is the code that sets the routing one line at a time.

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

Collective setting (resource-based routing)

You can write multiple routing configurations 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
  end

Same as personalized 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'
  end
* as option

You can specify “XXX”** as Prefix by setting **“as:’XXX’“.

resource (singular resource)

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

Also note that the controller is plural.

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

Same as personalized 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'
  end

How to describe advanced routing

Resource-based routing restrictions

When you want to use a part of the routing action of resources/resource Specify “only option” and “except option”.

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

    Uses other than #index/show/edit/update/destroy actions
    resources :books, except: [:index, :show, :edit, :update, :destroy]
  end
   $ 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 action for resource-based routing

In addition to the 7 basic Rails actions, you can add actions using “member routing” and “collection routing”.

What is member routing?

It 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'
      end
    end
  end
  $ rails routes

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

collection What is routing?

It is a routing method that does not include the URI path ** “:id” **. The code is written in the same way as the member route.

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. If there is an “id” in the path, it means that “the required data is specified by the management number when the action is executed”.

For example, if you explain with 7 basic actions of Rails index/new/create actions do not have “id” in the path. The reason is that we don’t need a specific data to display a list, and the data to be registered does not have an “id”.

On the contrary, show/edit/update/destroy actions You can view, change or delete certain registered data The “id” is included in the path because the data cannot be known without the “id”.

Nested resource routing

What is nesting?

It means “nesting”. Indicates that the route is described by putting the child element in the parent element in a nested structure.

Example) Nested resource routing


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

In this example, a parent element called books has a nested 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, the reviews (child element) is bound to a specific book (parent element). If you check the route of reviews (child element), it will be 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

There is a nesting effect on the Prefix and URI Pattern items.

Effect on Prefix

The parent element is placed before the child element. It is a prefix that contains parent elements (book) 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 is a URI Pattern that contains the parent element (book) called /books/:book_id/reviews. The part of /books/:book_id becomes a path that represents a specific parent element. “Which parent element the child element is connected to” will be explicitly indicated.

That’s it.