带有查询字符串的 Rails 路由 [英] Rails Routing with Query String

查看:23
本文介绍了带有查询字符串的 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.

我的类别对象有一个类型(字符串)、一个颜色(字符串)和许多产品.我想创建一个简单的网络服务,让调用者通过传入类别的类型和颜色来获取类别的所有产品:

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'

在控制器中,你将在 params 散列中有 catType 和 color:

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

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

有更好的方法吗?可能是的,但这取决于您的需求.如果你总是有 catType 和颜色参数,那么你可以像这样添加路由:

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 散列访问这些参数.您的网址将如下所示:

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天全站免登陆