登录时没有验证错误,在使用Devise / Rails注册时出现

时间:2014-03-03 19:44:39

标签: ruby-on-rails devise

使用Devise with Rails,但在模型中验证自己以提供自定义错误消息:

validates :email,
    :uniqueness => {:message => :unique_email},
    :presence => {:message => :email_missing}

YML:

unique_email: "Email address needs to be unique"
email_missing: "Email address can't be blank"

查看:

=@user.errors.messages.inspect

什么都不产生,一个空物!注册时,一切正常......

有什么想法吗?

编辑:

好吧,它正是这样的登录错误:

- flash.each do |name, msg|
    .standalone_form--message= msg

那么如何自定义这些消息(即来自yml文件)?就像我使用@user.errors.messages

一样

1 个答案:

答案 0 :(得分:0)

您应该使用locales来发送消息,因为Rails指南建议:

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "Email address"
    errors:
       models:
        user:
          attributes:
            email:
              blank: "can't be blank"
              unique: "should be unique"

注意:请勿使用以下内容,只是为了显示YAML问题

那说,关于你的错误,这应该有效:

validates :email,
  :uniqueness => {:message => "Email address should be unique"}

问题是您应该正确加载YAML文件:

创建名为config/error_messages.yaml的文件:

unique_email: "Email address needs to be unique"
email_missing: "Email address can't be blank"

添加Ruby文件config/initializers/load_error_messages.rb

ERROR_MESSAGES = YAML.load_file(Rails.root.join("config", "initializers", "config.yml"))

然后在验证上使用它:

validates :email,
  :uniqueness => {:message => ERROR_MESSAGES['unique_email']}

(资料来源:RailsCast #85