使用查询字符串进行Rails路由

编程入门 行业动态 更新时间:2024-10-27 06:21:46
本文介绍了使用查询字符串进行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:

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

或?

www.myapp/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/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/getProduct /...。但是您将在控制器中做更多的工作。您将可以通过以下方式访问 query :

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

params[:query]

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

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

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

So you have to parse it manualy.

更多推荐

使用查询字符串进行Rails路由

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

发布评论

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

>www.elefans.com

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