带有以斜杠结尾的约束的通配符路由 [英] Wildcard route with a constraint to end with trailing slash

查看:28
本文介绍了带有以斜杠结尾的约束的通配符路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个通配符路由,如下所示:

I have 2 wildcard routes that look like:

get '*country_path/', to: 'country#list', constraints: { country_path: /\/$/ }
get '*country_path/:title', to: 'country#show'

country#list 当 url 有斜杠时应该被调用.示例:

country#list should be called when the url has a trailing slash. Examples:

www.example.com/usa/california/
www.example.com/usa/california/abc/

country#show 没有尾部斜杠时应该被调用.示例:

country#show should be called when it does NOT have a trailing slash. Examples:

www.example.com/usa/californa/travel
www.example.com/usa/californa/average-income

目前我的约束似乎不起作用,因为所有请求都转到 country#list.

Currently my constraint doesn't seem to work as all requests go to country#list.

我的路线限制有什么问题?

What is wrong with my route constraint?

推荐答案

你应该问问自己,这是否真的是完成你正在尝试做的事情的最佳方式.网站通常不关心目录中的尾部斜杠.例如:

You should ask yourself whether this is really the best way to accomplish what you are trying to do. Websites in general do not care about trailing slashes in directories. For example:

www.facebook.com/username

会带你到同一个地方:

www.facebook.com/username/

绝大多数网站都是这样工作的,所以您现在尝试做的事情是违反网络约定的.如果您关心它,它肯定会对 SEO 产生影响.即使你不这样做,你也应该考虑一下在测试这些路线时会遇到的困难.你的测试会很脆弱,从长远来看这会导致很多挫折.

The vast majority of websites work like this, so what you are trying to do right now is against web conventions. It will certainly have ramifications for SEO, if you care about that. Even if you don't, you should think about the difficulties you will face when testing these routes. Your tests will be brittle and this will cause a lot of frustration in the long run.

我的建议是:如果您想区分 listshow,请将它们放入 URL.例如:

My advice would be this: if you want to distinguish between list and show, put those into the URL. For example:

www.example.com/usa/california/list
www.example.com/usa/california/abc/list

可以带用户到country#list,以california"和abc"为参数.同样:

Can take the user to country#list, with "california" and "abc" as parameters. Similarly:

www.example.com/usa/californa/travel/show
www.example.com/usa/californa/average-income/show

可以带用户到country#show.这要容易得多.它也更加标准和用户友好.如需更多信息,请参阅Rails 从外向内路由

Can take the user to country#show. This is significantly easier to do. It is also more standard and user-friendly. For more information, see Rails Routing from the Outside In.

这篇关于带有以斜杠结尾的约束的通配符路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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