Tintin81
Tintin81

Reputation: 10207

How to keep the locale during Ajax requests in Ruby on Rails?

I have an Ajax function in Rails where the chosen value of a select box changes the available options inside another:

# application.js
$("#project_person_id").change(function() {
    $.ajax({
        url: '/projects/get_billing_address_types',
        data: 'person_id=' + this.value,
        dataType: 'script'
    })
});

# get_billing_address_types.js.erb
$('#project_billing_address_type').html("<%= escape_javascript(options_for_select(@types)) %>");

Unfortunately, this doesn't work since I localised my app for two different languages.

When I now change the value of the first select box, I get an error inside the other:

<option value="h">translation missing: en.views.home</option>

Is there any way to pass the locale to javascript at all?

Thanks for any help.

Upvotes: 0

Views: 812

Answers (1)

agmcleod
agmcleod

Reputation: 13621

How are you preserving the URL in non XHR requests? You can simply pass it as a query string parameter to the url. Then use a before_filter to set the I18n locale to that passed parameter.

class ApplicationController < ActionController:Base

  before_filter :select_locale

  def select_locale
    I18n.locale = params[:locale] || "en"
  end

The application controller is generally where i do that sort of thing, but you can put it in a specific controller to restrict usage if you prefer.

Upvotes: 1

Related Questions