我已关注 this为 cancan 编写异常处理。
首先,我在"new"操作中有一个产品模型
这是英文语言环境文件:
# in config/locales/en.yml
en:
unauthorized:
manage:
all: "Not authorized to %{action} %{subject}."
预期的结果很好:
Not authorized to new Product.
但我的问题是现在我有另一个语言环境:.de
# in config/locales/en.yml
de:
unauthorized:
manage:
all: "Non autorisé à %{action} %{subject}."
然后我会得到
非自创新产品
我想要的是
Non autorisé à nouveau produit.
暂时我有 2 个选择来实现这一目标,
一个是我想我可以修改cancan中的源代码。
第二个是在它上面附加一些翻译的文本。
但是有什么原生的方式吗?
谢谢
最佳答案
I18n 支持模型和属性的名称。
在这种情况下,模型名称可以在翻译文件中指定后自动翻译。
前任。:
fr:
activerecord:
models:
product: "produit"
attributes:
product:
name: "nom"
manufacturer: "fabricant"
直接设置flash消息的情况下,可以使用I18n.t函数,传递action和subject参数。前任。:
flash.now[:error] = t('unauthorized', scope: 'manage.all', action: params[:action], subject: Product.model_name.human)
render 'new'
也许您想为 Action 的名称设置一些翻译,并使用 t(params[:action], scope: 'actions') 作为上面的 flash 消息或简单地使用 t('actions.new')。
fr:
actions:
new: "nouveau"
OBS:您可以使用 action_name (Rails 4) 或 controller.action_name (Rails 3) 而不是 params[:action]。
关于ruby-on-rails - rails cancan i18n 异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18809584/