Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Examples of advanced Rails 3.0 routes
Rails.application.routes.draw do
get '/(:locale)/products/(:category)/(page/:page).:extension',
:to => 'products#index',
:as => :products,
:constraints => {
:locale => /[a-z]{2}/,
:category => /.+?/,
:page => /\d+/
},
:defaults => {
:page => 1,
:extension => 'html',
:locale => 'en'
}
# products_path(:page => 1)
# => /products.html
# products_path(:page => 2)
# => /products/page/2.html
# products_path(:page => 2, :locale => 'de')
# => /de/products/page/2.html
# products_path('computers', :page => 2, :locale => 'de')
# => /de/products/computers/page/2.html
# products_path('computers/apple', :page => 2, :locale => 'de')
# => /de/products/computers/apple/page/2.html
# products_path('computers/apple')
# => /products/computers/apple.html
end
@ifightcrime

This comment has been minimized.

Copy link

commented Jul 12, 2011

is it possible to make it so if a user comes from lets say "/zx/products.html" the path will also default to "/zx/..." without having to specify "product_path(:locale => 'xz')"?

Kind of like "dynamic" defaults, rather than just using a fixed value for the default.

@pixeltrix

This comment has been minimized.

Copy link
Owner Author

commented Jul 13, 2011

@ifightcrime you can set a default url option for the :locale key in a before filter or override the default_url_options method - see this Stack Overflow answer for an example.

@ifightcrime

This comment has been minimized.

Copy link

commented Jul 13, 2011

Worked like a charm! thank you

@jgrannas

This comment has been minimized.

Copy link

commented Feb 12, 2015

So when you write:
products_path('computers', :page => 2, :locale => 'de')
How does the method know that computers is the category when its not being specified like the other params?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.