如果用户通过Facebook登录并且不提供他的电子邮件,我如何显示错误



在我的Web应用程序中,我有一个用于注册的宝石和2个Omniauth Gems(Google和Facebook(。情况如下:如果用户不提供与Facebook注册的电子邮件,则该应用程序会引起例外:Validation failed: Email can't be blank。这就是我的from_omniauth方法在用户模型中的样子:

def self.from_omniauth(auth, sign_in_resource = nil)
    # Get the identity and usesr if they exist
    identity = Identity.find_from_oauth(auth)
    # If a signed_in_resosurce is provided it always overrides the existing user
    # to prvent the identity being locked with accidentally created accounts.
    user = sign_in_resource ? sign_in_resource : identity.user
    # Create the user if needed
    if user.nil?
      # Get the exsiting user by email *Assuming that they provide valid_email address.
      user = User.where(email: auth.info.email ).first
      # Create the user if its a new registeration
      if user.nil?
        user = User.new email: auth.info.email, password: Devise.friendly_token[0,20]
        #Disable confirmation so we don't need to send confirmation email
        # user.skip_confirmation!
        user.save!
      end
    end
    # Associate the identity with the user if needed
    if identity.user != user
      identity.user = user
      identity.save!
    end
    # Get the basic information and create Profile, Address model
    unless user.profile.present?
      first_name = auth.info.first_name.present? ? auth.info.first_name : auth.info.name.split(' ')[0]
      last_name = auth.info.last_name.present? ? auth.info.last_name : auth.info.name.split(' ')[1]
      profile = Profile.new(user_id: user.id,
                            first_name: first_name,
                            last_name: last_name,
                            gender: auth.extra.raw_info.gender)
      profile.save(validate: false)
      address = Address.new(addressable_id: profile.id, addressable_type: 'Profile')
      address.save(validate: false)
    end
    user.reload
  end

user.save!上增加了例外,是否可以将用户重定向到其他页面,或者只是显示闪存消息?我知道,诸如重定向和其他内容之类的业务逻辑必须在控制器中执行。因此,也许有一种方法可以将我写的方法移动到控制器上?谢谢。

使用 rescue_from 在您的控制器中的类方法。

class YourController < ApplicationController
    rescue_from ::ActiveRecord::RecordInvalid, with: :validation_failed
    ...
    def validation_failed(exception)
       flash[:error] = exception.message
       redirect_to request.referer || root_path
    end
end

最新更新