Negma
Negma

Reputation: 25

Rails routes with optional parameters priorities

I have an strange issue in my routes file. This is the part that I need to understand This routes doesn't work

  # V3
  # V3 - Home Page
  match '/:locale' => 'v3/home#index', :constraints => V3Constraint, :as => :home
  # V3 - Search
  match '(/:locale)/products/search' => 'v3/products#search', :constraints => V3Constraint
  # V3 - Categories index
  match '(/:locale)/categories/(:parent_category((/*path)/:category))/(:full)' => 'v3/products#index', :constraints => V3Constraint, :as => :category
  # V3 - Prduct Page
  match '/:locale/products/:product' => 'v3/products#show', :constraints => V3Constraint, :as => :product
  match '(/:locale)/search_amazon' => 'v3/products#search_amazon', :constraints => V3Constraint
  # EOF V3

But this work

#V3 - Search
  match '(/:locale)/products/search' => 'v3/products#search', :constraints => V3Constraint
  # V3 - Categories index
  match '(/:locale)/categories/(:parent_category((/*path)/:category))/(:full)' => 'v3/products#index', :constraints => V3Constraint, :as => :category
  # V3 - Product Page
  match '/:locale/products/:product' => 'v3/products#show', :constraints => V3Constraint, :as => :product
  match '(/:locale)/search_amazon' => 'v3/products#search_amazon', :constraints => V3Constraint
  # V3 - Home Page
  match '/:locale' => 'v3/home#index', :constraints => V3Constraint, :as => :home

If I made the Home Page route have less priority than the others it works, but if it was on the top like the other this route: match '(/:locale)/search_amazon' => 'v3/products#search_amazon', :constraints => V3Constraint will be leading to the home page.

Can any please explain why this is has to happen ?

Thanks.

Upvotes: 0

Views: 281

Answers (1)

Islam Azab
Islam Azab

Reputation: 747

Having a route like this <yourdomain>/search_amazon will match the first one of these two routes

match '(/:locale)/search_amazon' => 'v3/products#search_amazon', :constraints => V3Constraint

In this case, it will match because locale is optional here.

match '/:locale' => 'v3/home#index', :constraints => V3Constraint, :as => :home

While here it will match making search_amazon as the value for locale.

Upvotes: 1

Related Questions