In a project I'm working on I'd like to add the same route for multiple resources. I know I can do this
resources :one do
collection do
post 'common_action'
end
end
resources :two do
collection do
post 'common_action'
end
end
I have at least 10 different resources which all need the same route, as each controller will have the same action. Is there a way to define this less repetitively?
%w(one two three four etc).each do |r|
resources r do
collection do
post 'common_action'
end
end
end
better way and support for rails 3.2
require 'action_dispatch/routing/mapper'
module ActionDispatch::Routing::Mapper::Resources
alias_method :resources_without_search, :resources
def resources(*args, &block)
resources_without_search *args do
collection do
match :search, action: "index"
end
yield if block_given?
end
end
end
You can extend the routing class:
class ActionDispatch::Routing
def extended_resources *args
resources *args do
collection do
post 'common_action'
end
end
end
end
...::Application.routes.draw do
extended_resources :one
extended_resources :two
end
Alternatively, you could even redefine the resources
method itself.
NB: I'm not sure whether ActionDispatch::Routing is the correct class name.