LoginSignup
0
0

DHH流のルーティングの書き方

Posted at

今回は私が現場で使用しているルーティング構成について自分のメモとしてまとめました。

DHH流ルーティングとは?

DHH流ルーティングとは、Railsの創始者であるDavid Heinemeier Hansson(DHH)の提唱するルーティング設計の方法論です。

DHH流ルーティングでは、リソースに対して標準的なCRUD操作(Create, Read, Update, Delete)を簡潔に定義し、カスタムアクションやネストリソースを最小限に抑えることで、ルートの複雑さを減らして記述を行うというものです。

つまり、デフォルトCRUDのindex , show, new, edit, create, update, destroyメソッドのみですべてを表現するということです。

具体的な設定例

・ 例1

  namespace :admins do
    root 'dashboards#index'

    resources :staffs
    resources :users do
      resource :enable, only: %i[ update ], module: :users
      resource :disable, only: %i[ update ], module: :users
    end
    resources :companies do
      resource :company_brand, only: %i[ edit update ], module: :companies
    end
  end

上記のような記述がDHH流のルーティングになります。

例えば resources :users であれば、今までであればデフォルトCRUDにenable、disableといったカスタムアクションを UsersController に設定していたと思います。

しかしDHH流ルーティングではupdateという単一のメソッドのみを持つ
Admins::Users::EnablesController という、新しいコントローラを持つことになります。
※userの status というカラムデータを有効にする( = update )するということからEnablesControllerを作成し、updateアクションを定義するということになります。

・ 例2

ここではRecipeに対して公開/非公開のアクションを付け加えた場合です。
カスタムアクションを追加するのであれば、コントローラは以下のようにな理ます。

class RecipesController < ApplicationController
  def index
  end
  # デフォルトのCRUDアクションが続く

  def publish
    # 公開処理
  end

  def unpublish
    # 非公開処理
  end
end

でもDHH流に書く場合には、ここがコントローラの分割されるポイントになります。

class Recipes::PublicationsController < ApplicationController
  def update
    # 公開処理
  end

  def destroy
    # 非公開処理
  end
end

recipe の配下に publication という公開/非公開を担うサブアクションを追加し、 update に公開処理を、 destroy に非公開処理を設定します。

ルーティングは下記のようになります。

resources :recipes do
  resource :publication, only: [:update, :destroy]
end

参照:https://tech.kitchhike.com/entry/2017/03/07/190739

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