In my multilingual Rails app I have a ProfilesController
. I am using a GET variable section
to split the view into different tabs. I am also storing that variable in a session
, so that it will be remembered across requests.
class ProfilesController < ApplicationController
before_action :signed_in_user
before_action :find_profile
before_action :set_section, :only => [:show, :edit]
def show
end
def edit
end
def update
if @profile.update_attributes(profile_params)
flash[:success] = t('profiles.flash_messages.profile_updated')
redirect_to edit_profile_path(:section => session[:section])
else
@title = t("views.#{session[:section]}")
render :edit
end
end
private
def find_profile
@profile = current_user.profile
end
def set_section
section = Profile::SECTIONS.include?(params[:section]) ? params[:section] : Profile::SECTIONS[0]
session[:section] = section
end
What I don't understand is why my update
action constantly redirects to the default_locale
rather than the locale the user chose and therefore stored in the session.
Can anybody tell me what I am missing here?
This is an excerpt of my routes.rb
file: (Please note that I am using a singular resource here since each user can have only one profile)
MyApp::Application.routes.draw do
scope '(:locale)' do
resource :membership
...
get 'change_locale', :to => 'locales#change_locale'
end
end
Update:
class ApplicationController < ActionController::Base
before_action :set_locale
protected
def set_locale
if params[:locale]
if I18n.available_locales.include?(params[:locale].to_sym)
I18n.locale = session[:locale] || params[:locale] || I18n.default_locale
end
end
end
def default_url_options
{ :locale => I18n.locale }
end
end
Try to use:
redirect_to edit_profile_path(:section => session[:section], :locale => I18n.locale)
or
class ApplicationController < ActionController::Base
before_action :set_locale
def default_url_options(options={})
{ locale: I18n.locale }
end
protected
def set_locale
I18n.locale = (session[:locale] || params[:locale]).to_s.downcase.presence || I18n.default_locale
end
end
this will help.