使用查询字符串进行Rails路由 [英] Rails Routing with Query String

查看:63
本文介绍了使用查询字符串进行Rails路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我需要从GET请求中传递值,但我不知道如何设置路由定义。

I have a problem where I need values passed in from a GET request and I don't know how to set up the routing definition.

我的Category对象具有类型(字符串),颜色(字符串)和许多产品。我想创建一个简单的Web服务,使调用者可以通过传递类别的类型和颜色来获取该类别的所有产品:

My Category object has a type(string),a color(string) and many products. I want to create a simple web service that lets the caller get all of a Category's products by passing in the Category's type and color:

http://www.myapp.com/getProducts?catType=toy&color=red

或?

http://www.myapp.com/categories/getProducts?catType=toy&color=red

如何为这种情况定义正确的路由?有没有更好的方法来以一种Restful的方式执行此操作...因为我知道Rails是Restful的,所以如果有一种正确地执行此操作的方法,那会更好。

How do I define the correct routing for this situation? Are there better ways to do this in a Restful manner... because I know that Rails is Restful, so if there is a way to do it "correctly" then that would be even better.

谢谢

推荐答案

第一个示例:

map.getproduct '/getProduct', :controller => 'your_controller', :action => 'your_action'

在控制器中,您将在参数哈希中使用catType和color:

In controller you will have catType and color in params hash:

params[:catType]
=> 'toy'
params[:color]
=> 'red'

还有更好的方法吗?可能是的,但这取决于您的需求。如果始终具有catType和color参数,则可以添加如下路由:

Is there better way? Probably yes, but it depends on your needs. If you will always have catType and color parameters, than you can add route like this:

map.getproduct '/getProduct/:catType/:color', :controller => 'your_controller', :action => 'your_action'

您将可以使用上例中的params hash访问这些参数。您的网址将如下所示:

You will have access to those parameters with params hash like in previous example. And your urls will look like this:

www.myapp.com/getProduct/toy/red

如果您的参数可能会更改,则可以使用路由遍历:

If your parameters may change, you can use route globbing:

    map.getproduct '/getProduct/*query', :controller => 'your_controller', :action => 'your_action'

然后,它将捕获所有具有 www.my的请求。 app.com/getProduct /...。但是您将在控制器中做更多的工作。您将可以通过以下方式访问 query

Then it will catch all request that has www.my.app.com/getProduct/... at the begining. But you will have more work in controller. You will have access to query with this:

 params[:query]

并用于 www.myapp.com/getProduct/color/red/ catType / toy 它会给出:

 params[:query]
 => ['color', 'red', 'catType', 'toy]

所以您必须解析手动操作。

So you have to parse it manualy.

这篇关于使用查询字符串进行Rails路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆