Rails 4路由约束,仅包含查询字符串或数字 [英] Rails 4 route constraints with query string or numbers only
问题描述
我正在尝试实施这两个有约束的路线:
I'm trying to implement these two routes with constraints:
get "products/:id", to: "products#show", constraints: { id: /\d/ }
get "products/:name", to: "products#search", constraints: { name: /[a-zA-Z]/ }
第一条路线应使用 localhost:3000 / products这样的URL触发/ 3
,最后一个应使用 localhost:3000 / products /?name = juice
触发。
The first route should trigger with an URL like localhost:3000/products/3
and the last one should trigger with localhost:3000/products/?name=juice
.
不起作用,我在Google上搜索了很多有关此问题的信息,但是我似乎找到了Ruby on Rails的第二或第三版的解决方案,并且其中大多数现已弃用。
Doesn't work, I googled a lot about this problem but I seem to find solutions for the second or third version of Ruby on Rails, and most of them are deprecated now.
有什么想法吗?谢谢。
推荐答案
如果您喜欢结果URL的外观,则可以按原样使用路由。不需要查询字符串。
You can use the routes as-is if you like the look of the resulting URLs. No need for a query string.
在您的控制器中,您会遇到一些类似的事情:
In your controller, you'd have something along these lines:
def show
@product = Product.find(params[:id])
# do stuff
end
def search
# I'm assuming your Product model has a `name` attribute
@product = Product.find_by(name: params[:name])
# do stuff
end
您可能希望对 find_by
返回的错误进行检查零,因为:name
不匹配任何东西,但这基本上就是它。
You probably want some error checking on find_by
returning nil because :name
did not match anything, but that's basically it.
您的route.rb将具有原始的路径定义:
Your routes.rb would have your original route definition:
get "products/:id", to: "products#show", constraints: { id: /[[:digit]]/ }
get "products/:name", to: "products#search", constraints: { name: /[[:alpha:]]/ }
您的应用程序应同时响应以下两个方面:
Your application should respond to both:
- 本地主机:3000 / products / 3
- 本地主机:3000 / products /果汁
这篇关于Rails 4路由约束,仅包含查询字符串或数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!