Translating custom error messages

2019-08-08 16:47发布

问题:

I have a form (using simple_form) which I want to implement support for translated error messages. All my translations appear with the exception of the error message.

My Customer model is:

class Customer < ActiveRecord::Base
  attr_accessible :name, :phone, :email, :contact_method

  validates_presence_of :phone, :email, :contact_method, :message => I18n.t(:required)
end

My fr.yml file

fr:
  name: 'Nom'
  phone: 'Téléphone'
  email: 'Courriel'
  contact_method: 'Méthode de contact'
  required: 'Requis'

My form is as follows:

= simple_form_for @customer do |f|
  = f.input :name, label: t(:name)
  = f.input :phone, label: t(:phone)
  = f.input :email, label: t(:email)

Is there something I'm missing?

回答1:

At first, you should use a Symbol with validates_presence_of. Don't translate it with I18n manually:

validates_presence_of :phone, :email, :contact_method, :message => :required

Secondly, add translation for your error message to your locale file like this:

activerecord:
  errors:
    models:
      customer:
        required: 'Requis'