flyingL123
flyingL123

Reputation: 8076

Ruby on Rails optional route segments

I'm trying to create two routes in my Rails application with optional parameters.

Here's my routes file:

get '(a)(/:area_id/)l/:location_id/(*url_title)', to: 'locations#show', as: :location
get 'a/:area_id/(*url_title)', to: 'areas#show', as: :area

Navigating to the following URLs correctly routes me to the right controller:

http://localhost:3000/a/1/l/2/seo-friendly-title.html
http://localhost:3000/a/1/seo-friendly-title.html

However, navigating to this url does not work:

http://localhost:3000/l/2/seo-friendly-title.html

I receive a No route matches error. Is it possible to make the a/:area_id portion optional when the l/:location_id portion is present?

Using Rails 4.2.4.

Upvotes: 1

Views: 123

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You could just add another route...

get 'l/:location_id/(*url_title)', to: 'locations#show'

There's no reason why two routes can't map to the same action.

Upvotes: 1

Related Questions