Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate (I18N) error texts raised by validations in the model (Ruby On Rails)

I am running an application on Ruby On Rails (3.1) and need to handle translations into various languages. I got my controller texts properly handled using the I18N feautures, but what about validations in models, especially those like this:

validate :valid_quantities?

def valid_quantities?
    if self.quantity*self.unitprice < 1.00
    errors.add("The transaction value", "is < 1.00")
    return false
end

How would I code this to provide support for other languages?
In addition, how to I handle the formatting of the numbers? I cannot call the ActionView helpers and user e.g. number_to_currency

like image 551
KKK Avatar asked Dec 04 '22 17:12

KKK


2 Answers

I would use this:

total_price = self.quantity*self.unitprice
errors.add(:transaction_value, :transaction_undervalued, { value: total_price })

IMHO you would better use a simple keyword like :transaction_undervalued, that way I18n look in several namespaces according to rails guides - i18n - error message scopes:

activerecord.errors.models.[model_name].attributes.transaction_undervalued
activerecord.errors.models.[model_name]
activerecord.errors.messages
errors.attributes.transaction_undervalued
errors.messages

*replace [model_name] with the model is using this validation

For the locales part, this is an example in /config/locales/en.yml

en:
  errors: &errors
    messages:
      transaction_undervalued: "The transaction value is %{value}. That is < 1.00"
like image 140
ivanxuu Avatar answered Apr 12 '23 22:04

ivanxuu


For standard validations, see http://guides.rubyonrails.org/i18n.html#error-message-scopes. For your custom validations, why don't you use I18n.t for that?

errors.add(:transaction_value, I18n.t("errors.attributes.transaction_value.below_1"))
like image 23
iGEL Avatar answered Apr 12 '23 23:04

iGEL