Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails i18n with translated model names

In my application I want to translate the validation error line: "3 errors have prohibited this order from being saved".

Obviously this can be made generic to fit all models that use this translation so in my de.yml locale template I got activerecord.errors.template.header like this:

  activerecord:
    errors:
      template:
        header:
          one:    "Konnte %{model} nicht speichern: ein Fehler."
          other:  "Konnte %{model} nicht speichern: %{count} Fehler."

Now the issue is how to call this validation without repeating myself a lot. Obviously you can simply call this through:

t('activerecord.errors.template.header', :count => @order.count, :model => Order)

But this won't translate Order (Order is called Bestellung in German)

I could go ahead and fix this by calling translate again inside the translate call:

t('activerecord.errors.template.header', :count => @order.count, :model => t('activerecord.models.#{Order}'))

But this really feels like a pretty bad solution and I am pretty sure there has to be a built in way to do this (as usually there is a cleaner way to do dirty stuff in Rails).

Any pointers on what the recommended way to deal with translations like this would be appreciated.

like image 371
Tigraine Avatar asked Jan 30 '26 22:01

Tigraine


1 Answers

Have you tried the following, using :model => Order.model_name.human instead of :model => Order?

t('activerecord.errors.template.header', :count => @order.count, :model => Order.model_name.human )
like image 171
Florent2 Avatar answered Feb 02 '26 12:02

Florent2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!