【rails】ルーティングをネストしてshallowオプションをつける

はじめに

railsでルーティングを作成する時、ネストしたあと簡略化するためにshallowオプションをつける

設定方法

postモデルとcommentモデルが1対多数の関係にあり、

わかりやすくするためにルーティングをネストする場合。

  resources :board, only: %i[index new create show] do
    resources :comments, only: %i[create], shallow: true
  end
board_comments_path   POST /boards/:board_id/comments(.:format)    comments#create

boards_path       GET   /boards(.:format)               boards#index
             POST /boards(.:format)               boards#create
new_board_path      GET   /boards/new(.:format)                   boards#new
board_path            GET   /boards/:id(.:format)                   boards#show

boardの方は普通のresourcesのときと同じです。

commentの方は、shallowオプションによって少し簡略化されています。

/boards/:board_id/comments/:id
↓↓
/boards/:board_id/comments

shallowオプションを指定すると、index,new,createなどのidを持たないアクション(コレクション)の場合は、idが省略されます。

反対に、show,edit,update,destroyのようなidが必要なアクション(メンバー)の場合は、ネストに含まれないようになります。

ネストしたURLの場合のform_with

コメント作成のときのform_with

<%= form_with model: comment, url:[board, comment], local: true do |f| %> ※省略形

<%= form_with model: comment, url: board_comment_path(board, comment), local: true do |f| %>

modelにcommentを指定することと、URLにboardcommentの両方使うため、引数を2つ指定するようにします。