【问题标题】:rails 3 validators & i18nrails 3 验证器和 i18n
【发布时间】:2011-07-04 19:02:00
【问题描述】:

所以我刚开始在 rails 3 中使用自定义验证器,但是我不确定是否可以使用现有的 activerecord i18n 语言环境文件。看来我不得不做

record.errors[attribute] << I18n.t('activerecord.errors.models.{model}.attributes.{attribute}.invalid_whatever') if ...

而不是以前我本可以完成的时候

:message => :invalid_whatever

我可以在我的 ActiveModel:Validator/EachValidator 类中使用速记来完成同样的事情吗?

【问题讨论】:

    标签: ruby-on-rails-3 internationalization validation


    【解决方案1】:

    我也遇到了同样的问题,终于找到答案了……

    record.errors.add(attribute,:invalid_whatever)
    

    【讨论】:

      【解决方案2】:

      如果您最终阅读了这个问题(在撰写本文时已经有几年的历史了),您可以为 Rails 4 尝试以下操作:

      在您的模型中:
      class Document < ActiveRecord::Base validates :date, date_in_present: {message: :custom_message} end

      在您的验证器中:
      class DateInPresentValidator < ActiveModel::EachValidator def validate_each(object, attribute, value) if(value.to_date >= Date.today) true else object.errors[attribute] << options[:message] end end end

      在您的 i18n yml 文件中:
      en: activerecord: errors: models: document: attributes: date: custom_message: Date is not in present

      我没有彻底测试这个。

      您还可以在自定义验证器中指定后备消息:
      object.errors[attribute] &lt;&lt; (options[:message] || "Display this message if message is not in options")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        相关资源
        最近更新 更多