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
end

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

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

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


Coffee is Good

in code

Replace Odd Numbers of Spaces Only

in code


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