I have followed this to write exception handling for cancan. First, I have a Product model in the "new" action Here is the english locale file:
# in config/locales/en.yml
en:
unauthorized:
manage:
all: "Not authorized to %{action} %{subject}."
The expected result is fine:
Not authorized to new Product.
But my question is now I have another locale ex: .de
# in config/locales/en.yml
de:
unauthorized:
manage:
all: "Non autorisé à %{action} %{subject}."
Then I'll get
Non autorisé à new Product
What I want is
Non autorisé à nouveau produit.
Temporarily I have 2 options to achieve this, One is I guess I could just modify the source code in cancan. The second is append some translated text to it. But is there something native way?
Thanks
I18n has support for Model and attributes' names.
In this case, the model name can be automatically translated once it is specified in the translation files.
Ex.:
fr:
activerecord:
models:
product: "produit"
attributes:
product:
name: "nom"
manufacturer: "fabricant"
In the case you set the flash message directly, you can use the I18n.t function and pass the action and subject parameters. Ex.:
flash.now[:error] = t('unauthorized', scope: 'manage.all', action: params[:action], subject: Product.model_name.human)
render 'new'
Maybe you will want to set some translations for actions' names and use t(params[:action], scope: 'actions') for the flash message above or simply use t('actions.new').
fr:
actions:
new: "nouveau"
OBS: you could use action_name (Rails 4) or controller.action_name (Rails 3) instead of params[:action].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With