当电子邮件已经存在并且帐户处于活动状态时,设计自定义错误消息 [英] devise custom error message when email already exists and account is active

查看:59
本文介绍了当电子邮件已经存在并且帐户处于活动状态时,设计自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设计好的用户模型,并且有一个活动列,该列指示用户是否处于活动状态.试用期结束后,除非用户注册其中一个计划,否则该帐户将处于非活动状态.

I have a User model with devise and have a active column which indicates if the user is active or not. After the trial period is over the account will be inactive unless the user sign up for one of the plans.

当电子邮件已经存在时,我正在使用如下所示的设计向用户显示自定义错误消息

I am currently showing custom error message to the users when email already exists using devise like below

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              taken: 'This email address has been used already. Please contact support if you would like more access'

但是,有时在试用期内拥有有效帐户的用户会尝试再次注册,在这种情况下,我想显示其他错误消息,例如请登录__sign__in__link"

However sometimes a user with active account in trial period tries to sign up again, in that case i want to display a different error message something like 'Please sign in __sign__in__link'

当电子邮件已经存在且帐户处于活动状态时,有条件地显示错误消息的正确方法是什么?

What would be proper way to display error message conditionally when email already exists and account is active?

谢谢.

推荐答案

处理此问题的方法并不是真正通过验证来进行,因为验证不具有您在应用程序流中所处位置的上下文.

The way to handle this isn't really through a validation since validations don't have the context of where you are in the application flow.

仅在表单上显示一个小错误对用户的帮助就不如显示Flash消息了.

And just displaying a little error on the form is a lot less helpful to the user then displaying a flash message.

Devise使这相当容易,因为 Devise :: RegistrationsController#create 的结果是让子类点击"流程:

Devise makes this fairly easy as Devise::RegistrationsController#create yields to let subclasses "tap into" the flow:


class MyRegistrationsController < Devise::RegistrationsController
  def create
    super do
      if has_duplicate_email? && user_is_active?
        flash.now("You seem to already have an account, do you want to #{ link_to(new_session_path, "log in") } instead?")
      end
    end 
  end

  private 

  def has_duplicate_email?
    return false unless resource.errors.has_key?(:email)
    resource.errors.details[:email].any? do |hash|
      hash[:error] == :taken
    end
  end

  def user_is_active?
    User.find_by(email: resource.email)&.active?
  end
end

# routes.rb
devise_for :users, controllers: {
  registrations: :my_registrations
}

这篇关于当电子邮件已经存在并且帐户处于活动状态时,设计自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆