Prosy thing with I18n and redirects (RoR) locales parameter is changing
-
12-11-2019 - |
Question
I tried to implement 'change language' feature at my app. I've looked through official guide http://guides.rubyonrails.org/i18n.html and everything was clear for me. Unfortunatly I dont know how to fix one issue. For example when I am accessing login form through link /en/login
everything is fine till I click on submit form.
After redirection param[:locale] is not passed as expected and I am getting default locales. Is there any "Rails-way" soultion to redirect with previously chosen locales? I guess that it is possible to pass every time param to redirect_to
but its kinda problematic to do on every controller.
My routes:
scope "(:locale)", :locale => /pl|en/ do
devise_for :users
resources :pages
get "/login" => "sessions#new"
post "/users/sign_in" => "sessions#create"
delete "/users/sign_out" => "sessions#destroy"
root :to => "pages#index"
resources :websites
end
match '/:locale' => 'pages#index'
App controller:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
Solution
as the same guide is recommending, you can add
class ApplicationController < ActionController::Base
def default_url_options(options={})
{ :locale => I18n.locale }
end
It will redirect your user to the proper localised root page
localhost:3000/?locale=pl
localhost:3000/?locale=en
....
OTHER TIPS
Try this
before_filter :check_for_previous_locale_in_cookie
def check_for_previous_locale_in_cookie
I18n.locale = cookies[:last_seen_locale].blank? ? cookies[:last_seen_locale] : (cookies[:last_seen_locale] = params[:locale] || I18n.default_locale )
end