我有一些代码可以使用Omniauth找到Oauth的用户。
如果用户在第1天用Facebook登录,请在第2天使用FB更改其电子邮件地址,并在第3天重新登录我的应用程序我想更新存档的电子邮件地址。
以下代码应同步电子邮件地址。 我使用AwesomePrint将电子邮件地址写入控制台,它们是不同的。但是,save返回true但电子邮件地址不会更新?
def self.find_or_create_for_oauth(auth)
social_identity = SocialIdentity.find_for_oauth(auth.provider, auth.uid)
email = auth.info.email
if social_identity.nil?
user = find_by_email(email)
if user.nil?
# create user for email with random password
end
social_identity = user.social_identities.create!(
provider: auth.provider,
uid: auth.uid
)
end
user = social_identity.user
ap user.email # email address 1
ap email # email address 2
if user.email != email
user.email = email
ap user.save! # returns true
end
user # still has email address 1
end
除了这两个以外,我删除了所有控制台写入:
if user.email != email
user.email = email
puts user.email
user.save!
puts user.email
end
我的控制台会返回这些(假的)电子邮件地址:kaylin.waters@wilderman.co.uk& grover@dickens.us。保存正在重置电子邮件地址而不是保存它。
所以我决定只发布下面的整个方法,以防它们发生奇怪的事情:
class User
has_many :social_identities, dependent: :destroy
def self.find_or_create_for_oauth(auth)
social_identity = SocialIdentity.find_for_oauth(auth.provider, auth.uid)
email = auth.info.email
if social_identity.nil?
user = find_by_email(email)
if user.nil?
random_password = generate_password
user = User.new(
email: email,
password: random_password,
password_confirmation: random_password)
user.skip_confirmation!
user.save!
end
social_identity = user.social_identities.create!(
provider: auth.provider,
uid: auth.uid
)
end
user = social_identity.user
if user.email != email
user.email = email
puts user.email
user.save!
puts user.email
end
user
end
end
class SocialIdentity < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :provider, presence: true
validates :uid, presence: true,
uniqueness: { scope: [:provider, :deleted_at] }
acts_as_paranoid
def self.find_for_oauth(provider, uid)
where(provider: provider, uid: uid).first
end
end
答案 0 :(得分:2)
您是在执行方法之后检查db状态还是只依赖于这些put?
有时候写puts user.reload.email
无论如何,我会分析日志以查看是否没有任何验证或回调被触发,这会回滚更改或以任何其他方式粘贴进程。另外,我会尝试user.update_column('email', email)
来查看是否有效。 update_column
会跳过任何验证或回调。