Passing locale via header or URL param are not changing the rails default locale

When i'm trying to make a request passing the param locale, i18n are not changing the default locale

ApplicationController

before_filter :set_locale
respond_to :json

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

My Model

class FoodType < ActiveRecord::Base

  default_scope where(locale: I18n.locale)

FoodTypesController

def index   
  render json: FoodType.all
end

But in the console, the query doesnt change. Still passing the locale from previous request

passing locale = pt-BR 

FoodType Load (0.4ms)  SELECT "food_types".* FROM "food_types" WHERE "food_types"."locale" = 'en'

Upvotes: 0

Views: 272

Answers (1)

Steve
Steve

Reputation: 15736

Your scope is evaluated when the FoodType class is loaded. This means that it will always have the same (initial) value. You need to use a lambda for scopes like this that vary depending on some external variable (time is another example):

default_scope, lambda { where(locale: I18n.locale) }

Upvotes: 3

Related Questions