【问题标题】:Globalize: How to show in the view the current locale information全球化:如何在视图中显示当前的语言环境信息
【发布时间】:2014-11-03 21:48:24
【问题描述】:

我目前在使用 Globalize gem 时遇到了一点问题。

我解释一下目前的情况: 我有一个名为 Question 的模型。创建它后,没有存储任何数据,我在模型中添加了以下几行:

class Question < ActiveRecord::Base
  translates :wording, :answer1, :answer2, :answer3, :answer4
end

然后,我创建了一个迁移来创建翻译表

class CreateTranslationsTable < ActiveRecord::Migration
    def up
        Question.create_translation_table! :wording => :string, :answer1 => :string, :answer2 => :string, :answer3 => :string, :answer4 => :string
    def end

    def down
        Question.drop_translation_table!
    def end

我的默认语言环境是 :en。之后我添加了一些数据。

如果我执行rails c 并输入命令Question.first.wording 一切正常。 虽然当我在'rails c'中执行I18n.locale = :es然后我执行Question.first.wording时仍然显示我放在开头的英文文本。

我尝试了一件似乎对我有帮助的事情,那就是我删除了所有已翻译的列(如迁移数据后在 Globalize 文档中指定的那样。在我的情况下,我一开始没有任何数据要迁移)。之后我进行了回滚(它取回了我从问题模型中删除的列),然后用I18n.locale = :es 执行Question.first.wording 让它工作。这意味着Question.first.wording 返回nil

之后,我按照 Ruby on Rails 指南中的说明实现了“Locale from Url Params” 这意味着第一个 URL 参数是 ':locale' 参数。 现在的问题是:视图仍然以英文显示信息,因为我输入的 URL 是 http://localhost.com/es/questions/

如何让它在视图中显示西班牙语信息?

【问题讨论】:

    标签: ruby-on-rails-4 globalize


    【解决方案1】:

    我的错。我从文档中解释了用于设置 url 的代码块(在 application_controller.rb 中):

    def default_url_options(options={})
        { locale: params[:locale] }
    end
    

    实际上会设置“I18n.locale”变量。我所做的是接下来解决这个问题(在 application_controller.rb 中):

    before_action :change_to_current_locale 
    def change_to_current_locale
        I18n.locale = params[:locale]
    end
    

    这让它起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多