Translating custom error messages

时光毁灭记忆、已成空白 提交于 2019-12-14 04:00:33

问题


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'


来源:https://stackoverflow.com/questions/12955208/translating-custom-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!