LoginSignup
6
7

More than 1 year has passed since last update.

Railsのルーティングパターン

Last updated at Posted at 2022-02-21

自分の覚書として残します(随時更新予定)

環境:

Rails: 6.0.4
Ruby: 3.1.0

一般的なルーティング

Rails.application.routes.draw do
  resources :blogs
end

スクリーンショット 2022-02-22 7.38.12.png

単数系

Rails.application.routes.draw do
  resource :blog
end

スクリーンショット 2022-02-22 7.39.04.png

確認画面をはさむ

Rails.application.routes.draw do
  resources :blogs do
    collection do
      post 'confirm'
    end
  end
end

スクリーンショット 2022-02-22 7.40.20.png

親子関係を表す

Rails.application.routes.draw do
  resources :blogs do
    resources :comments
  end
end

スクリーンショット 2022-02-22 7.41.43.png

idを持たないアクション(index/new/create)のみを親のスコープの下で生成する

Rails.application.routes.draw do
  resources :blogs do
    resources :comments, shallow: true
  end
end

スクリーンショット 2022-02-22 7.42.45.png

ログイン中のユーザーのプロフィールを /profile で表示したい場合

Rails.application.routes.draw do
  resources :users
  get 'profile', to: 'users#show'
end

参考記事: Railsのルーティング

スクリーンショット 2022-02-22 7.53.56.png

ルーティングに名前をつけたい場合

get 'exit', to: 'sessions#destroy', as: :logout

スクリーンショット 2022-02-22 8.13.51.png

名前空間を活用する

Rails.application.routes.draw do
  namespace :admin do
    resources :articles
  end
end

スクリーンショット 2022-02-22 8.20.50.png

参考記事: Railsガイド

6
7
1

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
6
7