Rails保存返回true但不保存任何内容

我有一些代码使用Omniauth为Oauth找到一个用户。

如果用户在第1天用Facebook登录,请在第2天使用FB更改其电子邮件地址,并在第3天重新登录我的应用程序我想更新文件中的电子邮件地址。

以下代码应同步电子邮件地址。 我使用AwesomePrint将电子邮件地址写入控制台,它们是不同的。 但是,保存返回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 

您是在执行方法之后检查db状态还是只依赖于这些put? 有时写puts user.reload.email是好事

无论如何,我会分析日志以查看是否没有任何validation或回调被触发,这会回滚更改或以任何其他方式粘附该过程。 另外,我会尝试使用user.update_column('email', email)查看是否有效。 update_column跳过任何validation或回调。