以不同语言而不是英语返回错误消息

时间:2017-07-27 09:12:15

标签: ruby-on-rails

例如:
错误 400 Bad Request 的响应,收到的消息类似于 param缺失或值为空:user 。我们是否有一种配置文件可以根据发送的参数返回错误消息,所以如果我发送param {lang:" French"}它会返回相应的错误消息但是用法语(The将从该配置文件中检索消息)我的想象力类似于以下内容。

400:
en:        "param is missing or the value is empty."
french:    "paramètres non trouvé"

1 个答案:

答案 0 :(得分:0)

在rails中你必须使用 / app / config / locales 文件夹中的本地化文件

例如,如果您的应用程序(英语和法语)有2个区域设置,您将拥有2个YAML文件: 的 /app/config/locales/en.yml

<强> /app/config/locales/fr.yml

本地化密钥将由相关的本地化文件提供。 例如: 的 /app/config/locales/en.yml

en:
  some_error_occurred: "Some error occurred."

<强> /app/config/locales/fr.yml

fr:
  some_error_occurred: "Une erreur s'est produite."

然后在您的控制器或视图中,您可以显示相关消息,如下所示:

I18n.t('some_error_occurred', locale: :en)

如果您没有明确的区域设置参数,则将使用当前区域设置。

在您的情况下,您应该将场景处理到控制器中,然后呈现包含相关消息的正确视图。

本地化功能强大,要正确理解您应该真正阅读相关文档的每个方面:http://guides.rubyonrails.org/i18n.html