Rails 3, create a new route for every resource

六眼飞鱼酱① 提交于 2019-12-23 02:22:40

问题


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.



来源:https://stackoverflow.com/questions/5246665/rails-3-create-a-new-route-for-every-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!