如何在动态分段中使用Rails 3路线 [英] How to Use Rails 3 Routes with Dynamic Segments
问题描述
在我的Rails 3.2应用程序中,有一个运动模型,其属性为muscle_group和grade_level。我在config / routes.rb中为其定义了以下带有动态细分的路由:
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"
正在运行 bundle exec耙路径
确认路线确实存在:
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 =腹部
- grade_level = 1
但是当我将浏览器指向 http:// localhost:3000 / abdominal / grade-1 / 5 ,我得到:
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?
推荐答案
我使用的路由声明几乎可以正常工作。出于某些原因,使用连字符而不将 grade_level
作为自己的 /
分隔的子字符串不存在问题。当我切换到使用路由声明时:
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:
match "/:muscle_group/grade/:grade_level/:id" => "exercises#show"
而不是原始版本:
match "/:muscle_group/grade-:grade_level/:id" => "exercises#show"
http:// localhost:3000 / abdominal / grade / 1/5 是有效的路由。
我宁愿使用连字符这条路线,并希望我知道如何进行此工作,但这不是重中之重。如果有人知道如何使其与连字符一起使用,请告诉我。
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 3路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!