STUDY MEMO

学習のメモ書き

<Ruby on Rails> ルーティング:shallowオプション

参考文献:Rails のルーティング - Railsガイド

shallowオプション

shallowオプションとは、深いネスト(入れ子構造)を避けるためにcollectionだけを親のスコープ下で生成させるオプションのこと。
idを含めないアクション(collection):index/new/create
idを含むアクション(member):show/edit/update/destroy
以下の例だとネストが深くなっていることがわかる。

# routes.rb
resources :articles do
    resources :comments
end

Image from Gyazo

これを踏まえて、ネストを浅くすると以下のような記載になる。

# routes.rb
resources :articles do
    resources :comments, only: [:index, :new, :create]
end
  resources :comments, only: [:show, :edit, :update, :destroy]

以上はshallowオプションを使用することによって、より簡潔な記載で実現できるようになる。

# routes.rb(:shallowオプションあり)
resources :articles do
  resources :comments, shallow: true
end

rails routes実行結果は以下のようになる。 Image from Gyazo