1

I'd like the have the following routes:

sports/1

calls the show method for sport with id = 1.

sports/about/1

shows an "about" page for sport with id = 1.

Right now I have:

 resources :sports

in routes.rb.

If I try to go to

sports/about/1

I get an error because of course no sport has id = about.

Can I do something like this?

Edit

To clarify, I just have an about action in my sports_controller. Thanks for both methods though (controller and action)

4 Answers 4

4

You can do almost anything you want with rails routes.

EDIT: Now a more complete (and correct) solution:

First you declare a new REST action in the sports resource:

resources :sports do
  get 'about', :on => :member
end

Then, to change the normal URL behavior url/sports/id/about to url/sports/about/id you should use:

match 'sports/about/:id', :controller => 'sports', :action => 'about'}
4
  • What this does is call an "about" action inside the sports controller. Is that what you want or you actually have an abouts controller? Feb 24, 2012 at 20:22
  • I just have an "about" action Feb 24, 2012 at 20:32
  • I get a undefined local variable or method map' for #<ActionDispatch::Routing::Mapper:0x007ffd33d54228>`. Is this the 3.2.1 syntax? Feb 25, 2012 at 22:37
  • Try using "match" instead of "map.connect" Feb 26, 2012 at 8:48
1

This should take care of your routes, but you really ought to check out the RailsGuides on the subject.

resources :sports do
  resources :about
end

This will give you routes like sports/:sport_id/about/:id. Of course you need to set the value of the sport in your form_for(@sport, @about) do |f| call or something like it.

1
  • the comment above makes a good point, I assumed presence of AboutsController.
    – rhodee
    Feb 24, 2012 at 20:27
0

In the routes.rb write the following in the same order

match 'sports/about/:id' => 'sports#show', :as => :sport
resources :sports

To show a sport use sport_path(@sport)

2
  • Will this make both sports/about/1 and sports/1 go to the same action? Feb 24, 2012 at 20:42
  • Yes, the url sports/1 will not match with the /sports/about/:id, but will match with the sports/1 which resources :sports generates. Both urls will call the show action in the sports controller
    – mohamagdy
    Feb 24, 2012 at 20:55
0

I think this is the most straight forward way to do it:

resources :sports do
 collection do
resources 'about'
end
end

Or maybe:

namespace :sports do
 resources 'about'
end

Depending on whether you want a separate about controller or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.