LoginSignup
0
0

More than 3 years have passed since last update.

Railsルーティング よく使用するメソッドのまとめ

Last updated at Posted at 2021-04-26

はじめに

ルーティングのメソッドについてふわっとした理解のままでいたので、改めて今まで使ってきたもの、プラスそのメソッド周りのオプションをまとめてみた。

・resources
・only(オプション)
・except(オプション)
・collection
・member
・on(オプション)
・namespace
・scope
・as(オプション)
・controller


resources

CRUD機能のルートを一式定義できる

resources :blogs

:only

onlyオプションは特定のルーティングを作成

resources :blogs, only: [:index]

:except

exceptオプションはonlyの反対で指定したアクションは作成しない

resources :blogs, except: [:edit, update]

resourcesにブロックを渡す

collection, member

collection

idを必要としないルーティングの生成/blogs/confirm

resources :blogs do
  collection do
    get 'confirm'
  end
end

member

idを必要とするルーティングの生成/blogs/1/preview

resources :blogs do
  member do
    get 'preview'
  end
end

on

onオプションはcollection, memberのブロック内にルーティングが1つしかない場合は省略して書くことができる。

resources :blogs do
  get 'confirm', on: :collection
end

resources :blogs do
  get 'preview', on: :member
end

namespaceとscope

namespace

多数のコントローラ群をまとめることができる
ファイル構成も指定される
これによりURL、名前付きルーティングヘルパー(パス)などが生成される

controllers/admin/users_controller.rb
namespace :admin do
  resources :users
end

Helper     HTTP  URI Pattern        Controller#Action
admin_users GET    /admin/users(.:format)  admin/users#index 

scope

URLのパスの指定のみ
ファイル構成、ルーティングヘルパーは変わらない

controller/articles_controller.rb
scope :blogs do
  resources :articles
end

Helper  HTTP  URI Pattern           Controller#Action
articles GET    /blog/articles(.:format)   articles#index

as

scopeにasオプションを使用すると、ルーティングヘルパーに名前をつけることができる
(他にも:modle, :pathを指定できる)

controller/articles_controller.rb
scope :blogs do
  resources :articles, as: 'hoge_articles'
end

例 ヘルパーのみ変更されてる

Helper       HTTP  URI Pattern            Controller#Action
hoge_articles GET    /blogs/articles(.:format)   articles#index

namespaceスコープは:moduleや:pathプレフィックスに加えて:asも自動的に追加される。


controller

コントローラーを指定してコードをまとめることができる。
構造と結びつけて記述することで可読性があがる

  controller :blogs do
    scope :blogs do
      resources :articles, as: 'hoge_articles'
    end
  end

ネストしたルーティング

親子関係をルーティングで表現できる
親に加えて、ネストされた子のルーティングも生成される

resources :admins do
  resources :users
end

(namespaceと何が違うの??ということで上記のnamespaceと同じコントローラー名で比較してみた。)
URL: /admins/:admin_id/users(.:format)親のidが追加されていた、以上

Helper       HTTP  URI Pattern                  Controller#Action
admins_users  GET   /admins/:admin_id/users(.:format)  users#index

※ネストは1回にとどめること、2回以上はルーティングが扱いにくくなる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0