如何从 Rails 3 路由获取段键?
我需要确定我正在处理的应用程序的当前路径中的路由段键的数量,尽管在相关的 Rails 3 源文件中进行了一些挖掘,但我无法弄清楚。
我知道如何使用 url_for
和 request
从当前路由构建路径,但我不知道如何实际到达 ActionController::Routing ::Route
映射到 url_for
正在使用的路由。如果我可以获得所需路由的实例,我只需调用 Route#segment_keys 即可获得所需的内容。
如果有人感兴趣,我这样做的原因是这样我可以使用选择下拉列表在资源之间切换,并停留在适用于当前所选资源的当前视图上,但仅当当前路径不包含时嵌套路径(即切换/resources/1/edit
到/resources/2/edit
,但不在之间切换>/resources/1/subresources/1
到 /resources/2/subresources/1
因为 subresource
数字 1 不是 resource< 的子资源/代码> 2).
I need to determine the number of route segment keys in the current path for an application I'm working on, and despite digging around for a bit in the related Rails 3 source files, I can't figure it out.
I know how to use url_for
and request
to build a path from the current route, but I don't know how to actually get to the ActionController::Routing::Route
that maps to the route url_for
is using. If I can get an instance of the route I need, I can just call Route#segment_keys and get what I need.
If anybody is interested, the reason I'm doing this is so I can toggle between resources with a select dropdown and stay on the current view that applies to the currently selected resource, but only if the current path doesn't contain nested paths (i.e. toggle /resources/1/edit
to /resources/2/edit
but do not toggle between /resources/1/subresources/1
to /resources/2/subresources/1
because subresource
number 1 is not a child of resource
2).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了需要执行类似操作的情况,因此我在 application_helper.rb 中添加了一个方法:
正如您所看到的,使用 request.fullpath.split("/") 创建一个分配给 url_path 的数组。从这里,我可以提取出我想要的内容或计算数组中的元素数量。我希望这能将您推向正确的方向。
I had a case where I need to do something like this, so I added a method in my application_helper.rb:
As you can see using the request.fullpath.split("/") creates an array I assign to url_path. From here, I can extract out what I want or count the number of elements in the array. I hope this pushes you in the right direction.
您需要所有段键还是只需要某种类型?
我能够用这段代码得到文字键
,这让我只得到文字段数组 - 我打赌你可以修改它来计算存在的段键的数量(或者对文字执行一次,对符号执行一次) )
Journey::Nodes::Cat
支持to_s
,它会为您提供用于构建路线的原始字符串,而to_regexp
将为您提供您可以针对request.path
运行正则表达式Do you need all the segment keys or just a certain kind?
I was able to get just the literal keys with this code
That got me just just the array of literal segments - I bet you could modify that to count the number of segment keys that exist (or do it once for literals and once for the symbols)
Journey::Nodes::Cat
supportsto_s
which will give you the original string used to construct the route andto_regexp
which will give you a regex you can run againstrequest.path
这样的事情会有帮助吗?它将路径解析为路由哈希。
Would something like this help? It resolves a path to a route hash.