evanrmurphy
evanrmurphy

Reputation: 1846

How to Use Rails 3 Routes with Dynamic Segments

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:

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?

Upvotes: 2

Views: 2186

Answers (2)

evanrmurphy
evanrmurphy

Reputation: 1846

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.

Upvotes: 2

jake
jake

Reputation: 2411

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

Upvotes: 1

Related Questions