Rails路由匹配查询参数

编程入门 行业动态 更新时间:2024-10-27 08:30:30
本文介绍了Rails路由匹配查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

轨道路由非常适合匹配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)的高级约束部分(guides.rubyonrails/routing.html)。

The following solution is based on the "Advanced Constraints" section of the "Rails Routing from the Outside In" rails guide (guides.rubyonrails/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路由匹配查询参数

本文发布于:2023-10-28 13:15:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536734.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   参数   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!