Janko
Janko

Reputation: 152

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.

Upvotes: 3

Views: 2792

Answers (1)

j-dexx
j-dexx

Reputation: 10416

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

Upvotes: 4

Related Questions