所以我已经安装了 Omniauth gem,它目前是用 Devise 实现的。
Devise 运行良好,但是设置 Omniauth 是一场战斗,我仍在努力解决这个问题。我正在使用 Omniauth 和 Twitter 身份验证。
问题:当我单击“使用 twitter 登录”图标时,它会将我重新定向到 twitter,然后提示我输入我的 twitter 凭据..一切都很好,直到它开始重定向(回调)。
当它尝试重定向到我的应用程序时,我收到以下错误:
AuthenticationsController#create 中的 NoMethodError
undefined method `[]' for nil:NilClass
app/models/user.rb:14:in `apply_omniauth'
app/controllers/authentications_controller.rb:14:in `create'
注册控制器:
class RegistrationsController < Devise::RegistrationsController
def create
super
session[:omniauth] = nil unless @user.new_record?
end
private
def build_resource(*args)
super
if session[:omniauth]
@user.apply_omniauth(session[:omniauth])
@user.valid?
end
end
end
身份验证控制器:
class AuthenticationsController < ApplicationController
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
elsif current_user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
else
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
end
end
end
User.rb(用户控制器)
class User < ActiveRecord::Base
has_many :authentications
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable, :timeoutable and :activatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation
# attr_accessible :title, :body
def apply_omniauth(omniauth)
self.email = omniauth['user_info']['email'] if email.blank?
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
end
def password_required?
(authentications.empty? || !password.blank?) && super
end
end
请阅读更新:
我刚刚在 RailsCast 之后遇到了这个问题。
该教程说要运行:
rails g nifty:scaffold authentication user_id:integer \ provider:string uid:string index create destroy
但是我的机器上没有漂亮的脚手架东西,我只是跑了
rails g 脚手架身份验证 user_id:integer \ provider:string uid:string index create destroy
其行为不同。它没有创建存根“index”、“create”和“destroy”控制器方法,而是在数据库中创建了字段。
如何删除字段?