通过标头或URL参数传递区域设置不会更改rails默认区域设置

时间:2023-01-29 09:10:33

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

当我试图通过param语言环境发出请求时,i18n没有更改默认语言环境

ApplicationController

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

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'

1 个解决方案

#1


3  

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):

加载FoodType类时,将评估您的范围。这意味着它将始终具有相同(初始)值。你需要对这样的范围使用lambda,这取决于一些外部变量(时间是另一个例子):

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

#1


3  

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):

加载FoodType类时,将评估您的范围。这意味着它将始终具有相同(初始)值。你需要对这样的范围使用lambda,这取决于一些外部变量(时间是另一个例子):

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