Все возможные ошибки проверки модели - PullRequest
8 голосов
/ 03 июня 2011

У меня есть форма с кучей полей и валидаций моделей.

Как я могу вернуть все возможные ошибки валидации, которые могут возникнуть?

Мне нужно, чтобы написать локали для всехиз них.

Я хочу получить такой список:

password blank
password too_short
password confirmation
login blank
login invalid
email blank
email too_short
email invalid

и т. д.

Ответы [ 2 ]

12 голосов
/ 03 июня 2011

В основном то, что говорит Пабло, за исключением того, что страница в документации по rails не показывает, как переопределить сообщения для конкретной модели и поля.Вот пример из одного из моих приложений:

activerecord:
  errors:
    full_messages:
      format: "{{message}}"    
    #define standard error messages, which we can overide on per model/per attribute basis further down
    messages:
      inclusion: "{{attribute}} is not included in the list"
      exclusion: "{{attribute}} is reserved"
      invalid: "{{attribute}} is invalid"
      confirmation: "{{attribute}} doesn't match confirmation"
      accepted: "{{attribute}} must be accepted"
      empty: "{{attribute}} can't be empty"
      blank: "{{attribute}} can't be blank"
      too_long: "{{attribute}} is too long (maximum is {{count}} characters)"
      too_short: "{{attribute}} is too short (minimum is {{count}} characters)"
      wrong_length: "{{attribute}} is the wrong length (should be {{count}} characters)"
      taken: "{{attribute}} has already been taken"
      not_a_number: "{{attribute}} is not a number"
      greater_than: "{{attribute}} must be greater than {{count}}"
      greater_than_or_equal_to: "{{attribute}} must be greater than or equal to {{count}}"
      equal_to: "{{attribute}} must be equal to {{count}}"
      less_than: "{{attribute}} must be less than {{count}}"
      less_than_or_equal_to: "{{attribute}} must be less than or equal to {{count}}"
      odd: "{{attribute}} must be odd"
      even: "{{attribute}} must be even"
      record_invalid: "Validation failed: {{errors}}"    
    models:
      quiz:
        blank: "{{attribute}} can not be blank"
      user_session:
        blank: "{{attribute}} can not be blank"
        attributes:
          login:
            invalid: "Please enter your user name"   
          password:
            invalid: "Please note that passwords are case sensitive"  

Я также изменил основной формат сообщений об ошибках, так как иногда я не хотел, чтобы имя поля было добавлено в начале сообщения.Итак, я изменил

errors:
  format: "{{attribute}} {{message}}"

на

errors:
  format: "{{message}}"    

Именно поэтому я затем указал {{attribute}} в моих последующих ошибках, чтобы вернуть его в большинстве, но не во всех случаях.

Обратите внимание, что я использую старый синтаксис {{var}} вместо %{var}.Однако применяются те же принципы.

3 голосов
/ 03 июня 2011

Последние переводы рельсов: rails-i18n .

Ошибки ActiveRecord находятся под lang : ошибки и lang : active_record вкаждый .yaml.

Также в вашем приложении по умолчанию в config / locales / en.yml.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...