如何使用具有动态路段的 Rails 3 路线
在我的Rails 3.2应用程序中,有一个带有属性muscle_group和grade_level的Exercise模型。我在 config/routes.rb 中使用动态段定义了以下路由:
# config/routes.rb
match "/:muscle_group/grade-:grade_level/:id" => "exercises#show"
运行bundle exec rake paths
确认该路由确实存在:
/:muscle_group/grade-:grade_level/:id(.:format) exercises#show
数据库包含锻炼记录为:
- id =
- 5muscle_group =“abdominal”
- grade_level = 1
然而当我将浏览器指向 http://localhost:3000/abdominal/grade-1/5,我得到:
Routing Error
No route matches [GET] "/abdominal/grade-1/5"
Try running rake routes for more information on available routes.
如何让这条具有动态段的路线正常工作?
In my Rails 3.2 application, there is an Exercise model with attributes muscle_group and grade_level. I've defined the following route with dynamic segments for it in config/routes.rb:
# config/routes.rb
match "/:muscle_group/grade-:grade_level/:id" => "exercises#show"
Running bundle exec rake routes
confirms that the route does indeed exist:
/:muscle_group/grade-:grade_level/:id(.:format) exercises#show
The database contains an Exercise record with:
- id = 5
- muscle_group = "abdominal"
- grade_level = 1
And yet when I point my browser to http://localhost:3000/abdominal/grade-1/5, I get:
Routing Error
No route matches [GET] "/abdominal/grade-1/5"
Try running rake routes for more information on available routes.
How can I get this route with dynamic segments to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用的路线声明几乎可以正常工作。由于某种原因,使用连字符而不使用
grade_level
作为其自己的/
分隔的子字符串会出现问题。当我切换到使用路由声明时:而不是原来的:
http://localhost:3000/abdominal /grade/1/5 就是一条有效的路线。
我更喜欢这条带有连字符的路线,并希望我知道如何使其发挥作用,但这不是首要任务。如果有人知道如何使其与连字符一起使用,请告诉我。
The route declaration I was using was almost functional. For some reason there is an issue with using a hyphen and not having
grade_level
as its own/
-separated substring. When I switched to using the route declaration:Instead of the original:
http://localhost:3000/abdominal/grade/1/5 is then a valid route.
I would prefer to have this route with the hyphen and wish I knew how to make that work, but it is not a top priority. If anyone knows how to make it work with the hyphen, please let me know.
Rails 中的操作包使用 to_param 来覆盖 URL 帮助程序生成 URL 的方式。看看这篇文章,它对此进行了解释。
http://www.seoonrails.com/to_param-for-better-looking -urls.html
Action pack in Rails uses the to_param to override how the urls get generated by the URL helpers. Take a look at this article, which explains it.
http://www.seoonrails.com/to_param-for-better-looking-urls.html