【问题标题】:Devise, Rails 5, custom errors for email设计,Rails 5,电子邮件的自定义错误
【发布时间】:2017-10-02 19:45:48
【问题描述】:

我在 Rails 5 和 Devise 上注册了 Ajax。这是registrations_controller.rb

build_resource(sign_up_params)
byebug
    if resource.save
        if resource.active_for_authentication?
            sign_up(resource_name, resource)
            return render :json => {:success => true}
        else
        expire_data_after_sign_in!
            return render :json => {:success => true}
        end
    else
        return render :json => {:success => false}
    end

使用byebug,当我尝试使用存在的电子邮件注册并通过键入resource.errors 进行调试时,我看到了:

<ActiveModel::Errors:0x00000007254a48 @base=#<User id: nil, email: "email@email.com", role_id: 0, created_at: nil, updated_at: nil>, @messages={:email=>["has already been taken"]}, @details={:email=>[{:error=>:taken, :value=>"email@email.com"}]}>

如果我在控制台输入resource.errors.messages,我会看到:

{:email=>["has already been taken"]}

我知道如何获取消息或设置示例:

if resource.errors.details[:email][0][:error] == :taken
     return render :json => {:error=> "Email already in use."}
end

或在模型中添加user.rb:

validate :email_uniqueness

def email_uniqueness
    self.errors.add(:email, 'Email is already in use') if User.where(:email => self.email).exists?
end

,但我想更改默认错误消息。我在整个项目中搜索了这条消息,但一无所获。

如果电子邮件已在使用中,我如何更改 Devise 中的错误消息?

【问题讨论】:

  • 您检查了语言环境文件吗?

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


【解决方案1】:

这是默认的 Rails 验证错误消息。阅读此http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

您可以像这样更改*.en.yml 文件中的消息:

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              taken: is already in use

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 2013-05-14
    • 2013-06-04
    • 2012-09-03
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2015-02-16
    相关资源
    最近更新 更多