我正在使用Rails
与omniauth合作,并尝试将Twitter,Facebook和Google连接起来进行身份验证,但仍然遇到此错误:
PG::Error: ERROR: duplicate key value violates unique constraint "index_users_on_email"
DETAIL: Key (email)=() already exists.
这是我的身份验证控制器:
class AuthorizationsController < ApplicationController
def create
authentication = Authorization.find_by_provider_and_uid(auth['provider'], auth['uid'])
if authentication
flash[:notice] = "Signed In Successfully"
sign_in authentication.user, event: :authentication
redirect_to root_path
else
athlete = Athlete.new
athlete.apply_omniauth(auth)
debugger
if athlete.save(validate: false)
flash[:notice] = "Account created and signed in successfully"
sign_in athlete, event: :authentication
redirect_to finalize_profile_path
else
flash[:error] = "An error has occurred. Please try again."
redirect_to root_path
end
end
end
def failure
render json: params.to_json
end
private
def auth
request.env["omniauth.auth"]
end
def resource(user_type)
user_type.downcase.to_sym
end
end
我认为正在发生的事情是,当运动员被创建时,它正在创建一个带有空白电子邮件地址并且唯一键失败的人...我怎么能绕过这个?我想我知道如何为谷歌整合解决这个问题,但由于Twitter没有回复电子邮件,这个问题不会自行解决
答案 0 :(得分:1)
这就是我能够让它发挥作用的方式:
class AuthorizationsController < ApplicationController
def create
authentication = Authorization.find_by_provider_and_uid(auth['provider'], auth['uid'])
if authentication
flash[:notice] = "Signed In Successfully"
sign_in authentication.user, event: :authentication
redirect_to root_path
else
athlete = Athlete.new(email: generate_auth_email(params[:provider]) )
athlete.apply_omniauth(auth)
debugger
if athlete.save(validate: false)
flash[:notice] = "Account created and signed in successfully"
sign_in athlete, event: :authentication
redirect_to finalize_profile_path
else
flash[:error] = "An error has occurred. Please try again."
redirect_to root_path
end
end
end
def failure
render json: params.to_json
end
private
def auth
request.env["omniauth.auth"]
end
def resource(user_type)
user_type.downcase.to_sym
end
def generate_auth_email(provider)
return auth.info.try(:email) unless provider == "twitter"
return "#{auth.uid}@twitter.com" if provider == "twitter"
end
end
我使用twitter uid创建了一封电子邮件,twitter.com是域名,因为Twitter没有返回电子邮件地址
希望这可以帮助将来的某个人