Nathaniel Rand Nathaniel Rand - 13 days ago 8
Ruby Question

Ruby / Rails / v5 - Routing Order - Root - Does the location of root mater in regards to the order on routes file?

Ruby / Rails / v5 - Routing Order - Root




Does the order of my routes file matter?

For example, does my "root" need to be at the top or bottom of the route file?




routes.rb

Rails.application.routes.draw do

#Static Pages
get 'static_pages/main'
get 'static_pages/about'
get 'static_pages/contact'
get 'static_pages/help'

# Root
root 'static_pages#landing'

end

Answer

Does the order of my routes file matter?

yes, it does in some cases where you're using a variable in the url.

Say you have a routes file like this:

  get ':page', to: "ages#page"
  get 'about', to: "pages#about"

The second one will never get hit because the first is catching the string about in the parameter page.

Writing root 'static_pages#landing' is the same as get '/', to: "static_pages#landing". Since this matches for an exact string (/) with no variables, it won't interfere with your other routes.