【问题标题】:How to override a model validates errors message in the model如何覆盖模型验证模型中的错误消息
【发布时间】:2013-09-01 21:46:30
【问题描述】:

我的应用是 Rails 3 + Devise。我正在为用户构建一个注册表单。如果用户不输入电子邮件地址,我正在努力提供有用的错误消息。

我相信 Devise 有一些魔力正在使这变得一团糟。在我的用户模型中,我有:

user.rb

validates :email,:presence => {:message => "XXXXXXX."}

我的 en.yml:

en:
    activerecord:
        attributes:
            user:
                fname: "First name"
                lname: "Last name"
                photo_content_type: "Picture"
        errors:
            messages:
                blank: "cannot be blank"
                too_short: "is too short (minimum %{count} characters)"
                too_long: "is too long (maximum %{count} characters)"
            models:
                user:
                    attributes:
                        email:
                            taken: "the email address %{value} has already been registered"
                        password:
                            too_short: "the password is too short (minimum %{count} characters)"

在我的注册页面中,如果用户没有输入电子邮件,我会收到以下@errors:

@messages={:email=>["cannot be blank", "XXXXXXX"]}>

为什么我会收到两条错误消息?我怎样才能只收到一条错误消息?我需要找到一种方法来删除“不能为空白”。可以在 user.rb 中覆盖吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 devise


    【解决方案1】:

    您可以让 Devise 完成验证,但更改其消息。根据guides,您应该为密钥activerecord.errors.models.user.attributes.email.blank 编写自定义消息,以便它优先于默认值:

    en:
    activerecord:
        attributes:
            user:
                fname: "First name"
                lname: "Last name"
                photo_content_type: "Picture"
        errors:
            messages:
                blank: "cannot be blank"
                too_short: "is too short (minimum %{count} characters)"
                too_long: "is too long (maximum %{count} characters)"
            models:
                user:
                    attributes:
                        email:
                            blank: "XXXXXXX."
                            taken: "the email address %{value} has already been registered"
                        password:
                            too_short: "the password is too short (minimum %{count} characters)"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-13
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多