2

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

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

用户.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 中覆盖吗?

4

1 回答 1

7

您可以让 Devise 完成验证,但更改其消息。根据指南,您应该为密钥编写自定义消息,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)"
于 2013-09-01T23:04:28.067 回答