How to Use Rails 3 Routes with Dynamic Segments

℡╲_俬逩灬. 提交于 2019-12-07 22:01:27

问题


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?


回答1:


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"

Instead of the original:

match "/:muscle_group/grade-:grade_level/:id" => "exercises#show"

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.




回答2:


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



来源:https://stackoverflow.com/questions/9222922/how-to-use-rails-3-routes-with-dynamic-segments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!