gpt4 book ai didi

ruby-on-rails - Rails 路由匹配查询参数

转载 作者:行者123 更新时间:2023-12-04 11:16:53 24 4
gpt4 key购买 nike

Rails 路由非常适合匹配 RESTful 风格 '/' URL 的分隔位,但我可以匹配 map.connect 中的查询参数吗?配置。我要不一样的 Controller / Action 根据 '?' 之后是否存在参数来调用.

我正在尝试这样的事情......

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 中的 Controller 可用即可。散列

最佳答案

以下解决方案基于“Rails Routing from the Outside In” rails guide (http://guides.rubyonrails.org/routing.html) 的“高级约束”部分。

在您的 config/routes.rb 文件中,包含一个识别器类是否匹配?方法,例如:

class FruitRecognizer
def initialize(fruit_type)
@fruit_type = fruit_type.to_sym
end

def matches?(request)
request.params.has_key?(@fruit_type)
end
end

然后使用类中的对象作为路由约束,如下所示:
map.connect "api/my/path", :contraints => FruitRecognizer.new(:apple), :controller => 'apples_controller', :action => 'my_action'

关于ruby-on-rails - Rails 路由匹配查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2811080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com