[Rails3] Issue in modifying locale and redisplaying page

In a test app, I have a drop-down selection to change the language of
the site.
I use an Ajax request to an action in which the locale is changed, and
the it's redirected to the home page
unfortunately, the locale seems to be changed but the home page
doesn't reflect the new language ..

application_controller.rb
.. before_filter :set_locale
  def set_locale
    I18n.locale = params[:locale]
  end

  def default_url_options(options={})
    {:locale => I18n.locale}
  end

jquery Ajax request in application.js

jQuery(document).ready(function() {
  // handle change events from language selector
  $("select[id^='language_']").change(function(event) {
    var selected = $("#" + event.target.id + " option:selected");
    var value = selected.val();
    $.ajax({
      data: 'locale='+ value,
      type: 'post',
      url: '/locale'
      });
  });
});

routes.rb
  match '/locale' => "welcome#switch_language"

welcome_controller.rb
..
  def switch_language
    I18n.locale = params[:locale].to_sym
    redirect_to root_url
  end

what could be wrong ?

thanks fyh

In a test app, I have a drop-down selection to change the language of

the site.

I use an Ajax request to an action in which the locale is changed, and

the it’s redirected to the home page

unfortunately, the locale seems to be changed but the home page

doesn’t reflect the new language …

That doesn’t surprise me…

application_controller.rb

… before_filter :set_locale

def set_locale

I18n.locale = params[:locale]

end

This filter will execute on your Ajax action (as you have a params[:locale]) but on your redirect it’s a fresh request without that parameter so it will fallback to default.

I’d imagine you want to store params[:locale] in the session[] or cookie[] arrays and then use that value if set.

Also, remember the browser will normally send a preferred language in the headers (Accept-language) so you can use that by default. I can’t remember if I18n.locale uses that (or just the system locale).

Finally, your default_url_options is only used when generating urls for links using url_for and related functions - it doesn’t set it as a default parameter on incoming request.

Cheers,

Andy