代码之家  ›  专栏  ›  技术社区  ›  Alex Zakruzhetskyi

如果用户通过Facebook登录,而desn没有提供他的电子邮件,我如何显示错误

  •  1
  • Alex Zakruzhetskyi  · 技术社区  · 7 年前

    在我的web应用程序中,我有一个用于注册的Desive gem和2个omniauth gem(谷歌和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! 是否可以将用户重定向到其他页面,或只是显示一条flash消息?我知道业务逻辑,例如重定向和其他东西,必须在控制器中执行。那么,也许有一种方法可以将我上面写的方法移动到控制器?谢谢你了。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Satendra    7 年前

    使用 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