67

I added in the route file:

map.show_book "/show_book/:name/year/:year", :controller => "book", :action => "show_version"

I also added:

map.show_book "/show_book/:name", :controller => "book", :action => "show_version"

to show the latest book without specifying the year.

But it doesn't work, it cannot find the route in "show_book/NAME" if I don't pass the year.

Do you have some ideas why it doesn't work ?

THANKS !

PS. I know that I can use year as parameter with "?year=XXXX", but I want to use the year as a part of the URL

Wazery
  • 13,971
  • 15
  • 55
  • 91
Alessandro De Simone
  • 3,692
  • 6
  • 26
  • 37

1 Answers1

125

Put the optional parts between parenthesis:

map.show_book "/show_book/:name(/year/:year)", :controller => "book", :action => "show_version"

and remove the second route.

Update

The above answer is only for rails 3 and above. Inverting the two routes definitions fixed the problem (see Alessandro's comment below).

Andrew
  • 12,513
  • 15
  • 53
  • 82
Benoit Garret
  • 13,552
  • 4
  • 56
  • 64
  • Wow, this it is very simple, but I think it is only for Rails3. I forgot to specify that the project is in rails 2.3. But I have find out that it's enough to use both routes, but in a correct order (I wrote it in a wrong order). Thanks – Alessandro De Simone Sep 02 '11 at 10:53
  • "Only" is no longer true, since this is valid in Rails 4, and likely future versions as well. – AlexQueue Dec 04 '14 at 22:11
  • 1
    Is there a way to have multiple optional parts in the same route with an unspecified order? Soa long the lines of... map.show_book "/show_book/:name((/year/:year)(/day/:day))" – Eric Walsh Apr 07 '15 at 20:06
  • 1
    @EricWalsh you should ask that as a question, you're much more likely to get an answer (haven't touched rails for a long time, I won't be of much use) – Benoit Garret Apr 07 '15 at 21:22
  • Thanks @BenoitGarret, I opened up a question (http://stackoverflow.com/questions/29501364/rails-3-route-with-multiple-optional-parameters) just wanted to see if anyone in the thread would be able to shed some light! – Eric Walsh Apr 07 '15 at 21:26
  • How to make attachments `:id` optional in a route like this: `PATCH /pages/:page_id/attachments/:id(.:format) attachments#update` defined by `resources :pages do resources :attachments, only: [:create, :destroy, :update] end ` – W.M. Aug 29 '17 at 17:13
  • Damn, been using Rails for over a decade and this is the first time I've seen this. F'ing magical. – Joshua Pinter Mar 08 '21 at 21:29