Ruby on rails 4 轨道4中的布线

Ruby on rails 4 轨道4中的布线,ruby-on-rails-4,controller,routes,Ruby On Rails 4,Controller,Routes,我正在将应用程序从3.2.4升级到我以前使用的Rails 4版本: match ':controller(/:action(/:id))(.:format)' match ':controller(/search)(.:format)' => ':controller#search' 现在我得到一个错误 C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action_dispatch/routing/mapper.rb:2

我正在将应用程序从3.2.4升级到我以前使用的Rails 4版本:

match ':controller(/:action(/:id))(.:format)'
match ':controller(/search)(.:format)' => ':controller#search' 
现在我得到一个错误

C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action_dispatch/routing/mapper.rb:239:in `default_controller_and_action': 
':controller' is not a supported controller name. This can lead to potential routing problems. See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use (ArgumentError)

我有大约10到15个不同的控制器,都使用搜索。是否可以使用类似的代码,而不是编写每个控制器来匹配
controller\search

我只需循环数组中的所有控制器,并动态定义每个控制器,如下所示:

%w(controller1 controller2 controller3).each do |controller_name|
  match "#{controller_name}(/search)(.:format)" => "#{controller_name}#search", via: :get
end
请注意,您现在需要通过先前不需要的选项添加
。我假设您的搜索是通过GET请求进行的,但可能是通过POST进行的

这种方法的另一个好处是,如果您现在检查您的路线,您将准确地看到定义了哪些路线,并且没有猜测:

GET        /controller1(/search)(.:format)         controller1#search
GET        /controller2(/search)(.:format)         controller2#search
GET        /controller3(/search)(.:format)         controller3#search

第二行是多余的,因为

match ':controller(/search)(.:format)' => ':controller#search'
覆盖

match ':controller(/:action)(.:format)'
这基本上是您的第一条线路定义

来自中的Rails文档

Rails 4.0要求使用match的路由必须指定请求 方法

所以你的路线应该是这样的

match ':controller(/:action(/:id))(.:format)', via: :get
还是这个

get ':controller(/:action(/:id))(.:format)'

谢谢你,比灵顿。此问题的解决方法对我有所帮助。您的解决方案仍然会给我错误:
default\u controller\u和\u action':“:controller”不是受支持的控制器名称。这可能会导致潜在的路由问题。
看起来您的第二个声明是多余的。第一行包括
GET/:controller(/:action(/:id))(:format):controller#:action
,这就是您在第二行要说的内容。换句话说,您的第二行可能写为
get':controller(/:action)(:format)
。。。或者第二行可以省略。我修改了上面的答案。