Reputation: 269
I would like to add a wildcard for multiple models. I added a wildcard route to the end of my routes file:
get '*city/*tag', to: 'cities#show'
This works. However, I would like to add multiple wildcards like this:
get '*city/*tag', to: 'cities#show'
get '*city', to: 'cities#show', as: :city
get '*tag', to: 'articles#show'
I just don’t know how to fix this because it always points to the cities controller. Any idea how this could be fixed?
Every suggestion to put me in the right direction is welcome!
Rens
Upvotes: 0
Views: 251
Reputation: 7522
The wildcard *
matcher for Rails will match any portion of the URL, similar to a Unix glob. As such, when given the route /foo
, your routes for both *city
and *tag
will match it. Rails simply picks the first route that matches, which is why you're seeing it always going to the cities controller.
You have a couple options:
Make your routes non-ambiguous. E.g.:
get 'cities/*city', to: 'cities#show', as: :city
get 'tags/*tag', to: 'articles#show'
get '*city/*tag', to: 'cities#show'
Is a route setup that is non-ambiguous, because the prefixes of cities
and tags
are matched first, before your wildcard routes. You could also do a more straightforward RESTful route structure.
Have your cities controller handle the case where params[:city]
is not a city, and redirect it to the articles controller in that case. This blends routing logic into your controller logic, though, so while it's possible I'd strongly suggest you go with option 1 instead.
Hope that helps!
Upvotes: 1