Routing with an optional parameter
35,240
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).
Comments
-
Alessandro De Simone almost 2 years
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
-
Alessandro De Simone almost 13 yearsWow, 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
-
AlexQueue over 9 years"Only" is no longer true, since this is valid in Rails 4, and likely future versions as well.
-
Eric Walsh about 9 yearsIs 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))"
-
Benoit Garret about 9 years@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)
-
Eric Walsh about 9 yearsThanks @BenoitGarret, I opened up a question (stackoverflow.com/questions/29501364/…) just wanted to see if anyone in the thread would be able to shed some light!
-
W.M. almost 7 yearsHow to make attachments
:id
optional in a route like this:PATCH /pages/:page_id/attachments/:id(.:format) attachments#update
defined byresources :pages do resources :attachments, only: [:create, :destroy, :update] end
-
Joshua Pinter over 3 yearsDamn, been using Rails for over a decade and this is the first time I've seen this. F'ing magical.