简体   繁体   中英

Rails routes: optional parameters in resourceful routes

Does anyone know if there is a way to add optional parameters to a URL for a given resource? That is, given:

resources :cars 

in the routes fiel, I'd like to have the year optionally attached to the end of the URL:

mysite.com/cars/coolcar/2015
mysite.com/cars/coolcar # Both point to the same resource

I know I could get along with the usual, non-resourceful routes:

get 'cars/:id(/:year)' 

But i'd like to know if there is a more 'elegant' way of doing it, since in my case it might need quite a lot of routes with optional params.

Thanks in advance.

You could do

resources :cars do
  member do
    get ':year', to: 'cars#show'
  end
end

Not sure if you'd class it as more elegant though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM