问题描述
轨道路由非常适合匹配RESTful样式的URL的'/'分隔位,但是我可以匹配 map.connect 配置。我希望根据’?控制器/动作。
Rails routes are great for matching RESTful style '/' separated bits of a URL, but can I match query parameters in a map.connect config. I want different controllers/actions to be invoked depending on the presence of a parameter after the '?'.
我正在尝试类似的操作...
I was trying something like this...
map.connect "api/my/path?apple=:applecode", :controller => 'apples_controller', :action => 'my_action' map.connect "api/my/path?banana=:bananacode", :controller => 'bananas_controller', :action => 'my_action'
出于路由目的,我并不关心参数的值,只要它可以在 params 哈希
For routing purposes I don't care about the value of the parameter, as long as it is available to the controller in the params hash
推荐答案
解决方案基于从外部进入的路线(Rails)的高级约束部分(http://guides.rubyonrails.org/routing.html)。
The following solution is based on the "Advanced Constraints" section of the "Rails Routing from the Outside In" rails guide (http://guides.rubyonrails.org/routing.html).
在您的config / routes.rb文件中,包括识别器类是否具有匹配项?方法,例如:
In your config/routes.rb file, include a recognizer class have a matches? method, e.g.:
class FruitRecognizer def initialize(fruit_type) @fruit_type = fruit_type.to_sym end def matches?(request) request.params.has_key?(@fruit_type) end end
然后将类中的对象用作路由约束,如:
Then use objects from the class as routing constraints, as in:
map.connect "api/my/path", :contraints => FruitRecognizer.new(:apple), :controller => 'apples_controller', :action => 'my_action'
这篇关于Rails路由匹配查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!