- 我有一个带有自定义验证的模型。我返回验证 使用 AJAX 将错误以 JSON 形式发送到 View 。
- 我需要显示错误 具有正确区域设置的消息,但消息 每个语言环境都以英语(默认)显示。
- 当我返回 I18n.locale 时 无论设置的区域设置是什么,它本身而不是消息(用于故障排除)都会显示“en”。
- Controller 或 View 中的 I18n 按预期工作,此问题 仅发生在模型中。
- 我对区域设置所做的唯一配置是在应用程序配置中设置默认区域设置,并在应用程序 Controller 中的每个操作之前设置区域设置。
- 我注意到的另一件事是,当我使用 root_path 而不提供区域设置时,它使用默认区域设置,而不是像应有的那样保留当前区域设置。我认为这些问题是相关的
编辑:
- 当我在controller#create中打印区域设置参数时,我得到nil。由于某种原因我根本没有区域设置参数。
模型文件:
validate :relevant_date_time
def relevant_date_time
errors.add(:date_error, I18n.t("validations.date_error")) unless date_time_is_relevant?
end
应用程序 Controller :
before_action :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
我是不是忘记了什么?
我查看的信息:
- http://guides.rubyonrails.org/i18n.html
- Access translation file (i18n) from inside rails model
- Rails 3 translations within models in production
- http://www.eq8.eu/blogs/10-translating-locales-for-rails-model-errors
- https://lingohub.com/frameworks-file-formats/rails5-i18n-ruby-on-rails/
- Change locale at runtime in Rails 3
最佳答案
如果您在 application_controller.rb 处设置区域设置,则它将仅在所有 Controller 和 View 中有效,而不在模型中有效。
所以你也必须在模型中设置区域设置。与您在 Controller 中所做的相同。
在 Controller
Model.new(params.merge(locale: I18n.locale))
内部模型
attr_accessible :locale
before_validation() do
I18n.local = locale
end
def relevant_date_time
errors.add(:date_error, I18n.t("validations.date_error")) unless date_time_is_relevant?
end
关于ruby-on-rails - 仅使用默认语言环境的 Rails 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40463334/