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

Lee*_*Lee 6 ruby ruby-on-rails

我有一些代码可以使用 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
Run Code Online (Sandbox Code Playgroud)

进一步更新:

我删除了除这两个之外的所有控制台写入:

if user.email != email
   user.email = email

    puts user.email
    user.save!
    puts user.email
 end
Run Code Online (Sandbox Code Playgroud)

我的控制台返回这些(假)电子邮件地址: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
Run Code Online (Sandbox Code Playgroud)

soc*_*ata 5

您是在执行方法后检查数据库状态还是仅依赖于这些放置?有时候写字很好puts user.reload.email

无论如何,我会分析日志以查看是否没有任何验证或回调被触发以回滚更改或以任何其他方式遵守流程。另外,我会尝试这样做user.update_column('email', email),看看是否有效。update_column跳过任何验证或回调。