我有这种方法,我可以从中检查提供者和uid属性,以便在创建新注册表或获取现有注册表之间进行选择。
这是将facebook登录集成到我的应用程序中。
如果我想检查已经在我的应用程序中注册的用户,只是不通过Facebook,使用他们的电子邮件地址作为搜索关键字,然后将来自Facebook的proivider和uid属性添加到该帐户,那么什么是一个好的逻辑?
def self.from_omniauth(hash)
where(provider: hash.provider, uid: hash.uid).first_or_create do |user|
user.email = hash.info.email
user.password = Devise.friendly_token[0,20]
user.username = hash.info.name
end
更新
类Users :: OmniauthCallbacksController<设计:: OmniauthCallbacksController
def facebook
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
我按照您使用方法
的建议更新了代码def self.from_omniauth(hash)
find_by_provider_and_uid(hash.provider, hash.uid) || find_by_omni_email(hash.info.email) || create_with_omniauth(hash)
end
def self.create_with_omniauth(hash)
u = User.new
u.provider = hash.provider
u.uid = hash.uid
u.email = hash.info.email
u.password = Devise.friendly_token[0,20]
u.username = hash.info.name
puts "tried to create_with+omniauth"
end
def self.find_by_omni_email(email)
User.where(email: email).first
puts "ran find_by_omni_email"
end
def self.find_by_provider_and_uid(provider, uid)
User.where(provider: provider, uid: uid).first
puts "ran find_by_provider_and_uid"
end
答案 0 :(得分:0)
以这种方式改变你的逻辑。它将检查所有场景
def self.from_omniauth(hash)
find_by_provider_and_uid(hash.provider, hash.uid) || find_by_omni_email(hash.info.email) || create_with_omniauth(hash)
end
def self.create_with_omniauth(hash)
u = User.new
u.provider = hash.provider
u.uid = hash.uid
u.email = hash.info.email
u.password = Devise.friendly_token[0,20]
u.username = hash.info.name
u.save
u
end
def self.find_by_omni_email(email)
User.where(email: email).first
end
#this方法默认提供以下活动记录。我添加了如果它没有或有一些变化
def self.find_by_provider_and_uid(provider, uid)
User.where(provider: provider, uid: uid).first
end