0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】名前空間でルーティングをグループ化する

Posted at

はじめに

ルーティング設定時に名前空間(namespace)でコントローラをグループ化する作業を記録します。

環境

  • Rails6.1.7
  • Ruby2.7.8

設定例

config/routes.rb
Rails.application.routes.draw do
  namespace :hoge do
    resources :fugas do
      collection do
        get 'piyo'
        post 'hogera'
      end
      member do
        get 'hogehoge'
      end
    end
  end
end

ルーティングの結果

_pathヘルパー        |HTTP Verb| パス                           | コントローラ#アクション 
piyo_hoge_fugas     | GET   | /hoge/fugas/piyo(.:format)        | hoge/fugas#piyo
hogera_hoge_fugas   | POST  | /hoge/fugas/hogera(.:format)      | hoge/fugas#hogera
hogehoge_hoge_fugas | GET   | /hoge/fugas/:id/hogehoge(.:format)| hoge/fugas#piyo
hoge_fugas      | GET   | /hoge/fugas(.:format)        | hoge/fugas#index
                | POST  | /hoge/fugas(.:format)        | hoge/fugas#create
new_hoge_fuga       | GET   | /hoge/fugas/new(.:format)         | hoge/fugas#new
edit_hoge_fuga      | GET   | /hoge/fugas/:id/edit(.:format)    | hoge/fugas#edit
hoge_fuga           | GET   | /hoge/fugas/:id(.:format)         | hoge/fugas#show
                    | PATCH | /hoge/fugas/:id(.:format)         | hoge/fugas#update
                    | PUT   | /hoge/fugas/:id(.:format)         | hoge/fugas#update
                    | DELETE| /hoge/fugas/:id(.:format)         | hoge/fugas#destroy
  • namespace

    • メソッド名や変数名などが衝突しないようにするための機能
  • resourcesルーティング

    • 各HTTPメソッドとコントローラ内のアクションを指すURLに対応づけられる
    • アクションごとにDB上の特定のCRUD操作に対応づけられる
  • collectionルーティング

    • idが付与されない
# 指定例
resources :users do
  collection do
    get 'hoge'
  end
end
# パス
/users/hoge
  • memberルーティング
    • idが付与される
    • コントローラ内でparams[:id]という形で受け取ることができる
# 指定例
resources :users do
  member do
    get 'hoge'
  end
end
# パス
/users/:id/hoge

補足

コントローラファイルにおいては、下記のようにルーティングを反映した書き方ができます。

  • コントローラディレクトリの構造
app
 ├─controllers
     └─  hoge
         └─ fugas_controller.rb
  • コントローラファイル
controllers/hoge/fugas_controller.rb
class Hoge::FugasController < ApplicationController
  def new
  end
end

おわりに

config/routes.rbに書くと煩雑になる場合には、下記のように名前空間ごとに分ける書き方もできます。

config
 └─ routes
     ├─ hoge.rb
     ├─ # namespaceごとに分けてファイルを作成 
config/routes/hoge.rb
Rails.application.routes.draw do
  # ルーティングを設定する
end
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?