2.8 ルーティングの「concern」機能
concernを使うことで、他のリソース内で使いまわせる共通のルーティングを宣言できます。concernは以下のようにconcernブロックで定義します。
先にconcernを設定しておく
concern :commentable do
resources :comments
end
concern :image_attachable do
resources :images, only: :index
end
concernを利用すると、
同じようなルーティングを繰り返し記述せずに済み、複数のルーティング間で同じ振る舞いを共有できます。
resources :messages, concerns: :commentable
resources :articles, concerns: [:commentable, :image_attachable]
message_comments GET /messages/:message_id/comments(.:format) comments#index
POST /messages/:message_id/comments(.:format) comments#create
new_message_comment GET /messages/:message_id/comments/new(.:format) comments#new
edit_message_comment GET /messages/:message_id/comments/:id/edit(.:format) comments#edit
message_comment GET /messages/:message_id/comments/:id(.:format) comments#show
PATCH /messages/:message_id/comments/:id(.:format) comments#update
PUT /messages/:message_id/comments/:id(.:format) comments#update
DELETE /messages/:message_id/comments/:id(.:format) comments#destroy
# 二種類のルーティングを作成している-----------------------------------------------------------------------------------------
messages GET /messages(.:format) messages#index
POST /messages(.:format) messages#create
new_message GET /messages/new(.:format) messages#new
edit_message GET /messages/:id/edit(.:format) messages#edit
message GET /messages/:id(.:format) messages#show
PATCH /messages/:id(.:format) messages#update
PUT /messages/:id(.:format) messages#update
DELETE /messages/:id(.:format) messages#destroy
# ------------------------------------------------------------------------------------------------------------------
article_comments GET /articles/:article_id/comments(.:format) comments#index
POST /articles/:article_id/comments(.:format) comments#create
new_article_comment GET /articles/:article_id/comments/new(.:format) comments#new
edit_article_comment GET /articles/:article_id/comments/:id/edit(.:format) comments#edit
article_comment GET /articles/:article_id/comments/:id(.:format) comments#show
PATCH /articles/:article_id/comments/:id(.:format) comments#update
PUT /articles/:article_id/comments/:id(.:format) comments#update
DELETE /articles/:article_id/comments/:id(.:format) comments#destroy
article_images GET /articles/:article_id/images(.:format) images#index
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
上のコードは以下と同等です。
resources :messages do
resources :comments
end
resources :articles do
resources :comments
resources :images, only: :index
end
scopeブロック内やnamespaceブロック内では、以下のように複数形のconcernsを呼び出すことでも上と同じ結果を得られます。
namespace :messages do
concerns :commentable
end
namespace :articles do
concerns :commentable
concerns :image_attachable
end