Omniauth会话NoMethodError

时间:2012-03-25 19:24:27

标签: ruby-on-rails session hash omniauth

我正在开发一个rails应用程序,允许用户使用omniauth通过facebook / twitter / linkedin登录。到目前为止,用户可以使用身份验证进行注册和创建帐户,但是他们必须通过验证,然后转发到注册页面,在那里他们必须输入有效的名称,用户名和电子邮件。如果可能的话,我希望使用request.env [“omniauth.auth”]哈希填写这些字段。

这是我的代码:

authentications_controller.rb

user = User.new 
user.apply_omniauth(omniauth)

if user.save
  flash[:notice] = "Signed in successfully."
  sign_in_and_redirect(:user, user)
else 
  session[:omniauth] = omniauth.except('extra')
  redirect_to new_user_registration_url
end

registrations_controller.rb:

def build_resource(*args)
  super
  if session[:omniauth]
    @user.apply_omniauth(session[:omniauth])
    @user.valid?
  end
 end

user.rb:

def apply_omniauth(omniauth)
  self.name = omniauth['user_info']['name'] if name.blank?
  self.email = omniauth['user_info']['email'] if email.blank?
  authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
end

该行:

self.email = omniauth['user_info']['email'] if email.blank?

导致此NoMethodError:

undefined method `[]' for nil:NilClass

会话[:omniauth]正在从apply_omniauth方法中的注册控制器传递到omniauth。如何在此会话中访问姓名和电子邮件?

由于

1 个答案:

答案 0 :(得分:5)

  1. 快速回答:

    omniauth.info.email # which is the same as omniauth['info']['email']
    
  2. 解释性答案:

    将此作为回调控制器的第一行:

    render :text => "<pre>" + env["omniauth.auth"].to_yaml and return    
    

    现在尝试登录,您将能够很好地了解返回的嵌套哈希的哈希值。