Har*_*ood 7 routes ruby-on-rails
Rails路由非常适合匹配URL的RESTful样式'/'分隔位,但我可以匹配map.connect配置中的查询参数.我想要调用不同的控制器/动作,具体取决于后面的参数的存在'?'.
我正在尝试这样的事......
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'
Run Code Online (Sandbox Code Playgroud)
出于路由目的,我不关心参数的值,只要它在params哈希中可用于控制器
小智 10
以下解决方案基于"Rails Routing from the Outside In"rails指南(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
Run Code Online (Sandbox Code Playgroud)
然后使用类中的对象作为路由约束,如:
map.connect "api/my/path", :contraints => FruitRecognizer.new(:apple), :controller => 'apples_controller', :action => 'my_action'
Run Code Online (Sandbox Code Playgroud)
除非有具体原因无法改变这一点,否则为什么不让它平静一点呢?
map.connect "api/my/path/bananas/:id, :controller => "bananas_controller", :action => "my_action"
如果你有很多参数,为什么不使用 aPOST或 aPUT这样你的参数就不需要通过 url 暴露出来呢?
| 归档时间: |
|
| 查看次数: |
6290 次 |
| 最近记录: |