Add sub-controller modules to Rails 5 routing concerns

in code

Routing concerns have been a thing since Rails 4, but this morning I ran into a real annoyance: the documentation doesn’t adequately explain how to pass a module, in cases where you use separate sub-controllers. More than that, even-what if I want to pass any other options?

Here’s what I came up with, using splats and blocks:

concern :likeable do |options|
  resource :like, only: [:create, :destroy], **options

resources :posts do
  concerns :likeable, module: :posts

resources :comments do
  concerns :likeable, module: :comments

The output routes appear thus:

comment_like DELETE   /comments/:comment_id/like(.:format)    comments/likes#destroy
             POST     /comments/:comment_id/like(.:format)    comments/likes#create
   post_like DELETE   /posts/:post_id/like(.:format)          posts/likes#destroy
             POST     /posts/:post_id/like(.:format)          posts/likes#create

March 20

in me

Happy Dissonance

in me


in ireland

Your email address will not be published. Required fields are marked *