Rails 3, create a new route for every resource

2019-05-31 12:49发布

问题:

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?

回答1:

  %w(one two three four etc).each do |r|
    resources r do
      collection do
        post 'common_action'
      end
    end
  end


回答2:

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


回答3:

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.