I have two languages which I support with German being the default (See routes.rb
below).
With my Post
model I can now create links like so:
link_to t('.title'), posts_path(1), locale: I18n.locale
This results in these URLs depending on the locale:
- /en/posts/1
- /posts/1
Since German is the default, I have to include the locale, or the links will end up pointing to the German representation. So I have to make sure to include the locale
parameter in all links to my resources.
To avoid this extra work as well as links pointing to the wrong locale I set up default_url_options
def default_url_options(options={})
{ locale: I18n.locale }
end
Credits go to Rails: changing locale and keeping page parameters.
My links are more concise now: link_to t('.title'), posts_path(1)
but the links don't look so nice now anymore:
- /posts?locale=de
- /posts?locale=en
Is there a way to get the non-parameterised versions of the links but using default_url_options
at the same time.
My routes.rb
for reference:
Rails.application.routes.draw do
scope '(:locale)/', locale: /en|de/, defaults: {locale: 'de'} do
root to: 'posts#index'
resources :posts
end
end