<Ruby on Rails> ルーティング:shallowオプション
shallowオプション
shallowオプションとは、深いネスト(入れ子構造)を避けるためにcollectionだけを親のスコープ下で生成させるオプションのこと。
idを含めないアクション(collection):index/new/create
idを含むアクション(member):show/edit/update/destroy
以下の例だとネストが深くなっていることがわかる。
# routes.rb resources :articles do resources :comments end
これを踏まえて、ネストを浅くすると以下のような記載になる。
# 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実行結果は以下のようになる。