2017-07-28 52 views
0

我用omniauth-kakao寶石通過SNS登錄的ActiveRecord :: RecordNotUnique(PG :: UniqueViolplicate鍵值違反唯一約束「index_users_on_email」通貨膨脹:ERROR:杜

然後我成功登錄,我得到令牌和。 SNS的個人資料。

但是,當其他用戶(不是我)已經通過SNS註冊,我遇到了錯誤

ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_email" 

這是代碼app/model/user.rb,使錯誤

def self.find_for_oauth(auth, signed_in_resource = nil) 
    identity = Identity.find_for_oauth(auth) 
    user = signed_in_resource ? signed_in_resource : identity.user 

    if user.nil? 
    email = auth.info.email 
    user = User.where(:email => email).first 
    unless self.where(email: auth.info.email).exists? 
     if user.nil? 
      user = User.new(
      profile_img: auth.info.image, 
      password: Devise.friendly_token[0,20] 
     ) 
     user.save!  #Error message said this line is problem 
     end 
    end 
    end 

    if identity.user != user 
    identity.user = user 
    identity.save! 
    end 
    user 
end 

另外,我做了兩個模型。 (Identity.rb參考User.rb)

Identity.rb有'Provider(sns)','User'列。 User.rb有用戶的信息,SNS列的配置文件。

當錯誤發生時,行加入Identity.rb和該行尚未在「用戶」列user_id說明。(加入其他人,不是隻添加USER_ID)

此外,行不加入User.rb從未

有什麼問題?

+0

https://stackoverflow.com/questions/18496223/possible-到指定唯一指數與 - 空值允許的功能於軌道-的ActiveRecord –

回答

0

如果你不能與用戶數據庫在下面的代碼保存email

if user.nil? 

    user = User.new(
     profile_img: auth.info.image, 

     password: Devise.friendly_token[0,20] 
    ) 
    user.save!  #Error message said this line is problem 
end 

應該是這樣:

if user.nil? 

    user = User.new(
     profile_img: auth.info.image, 
     email: email, 
     password: Devise.friendly_token[0,20] 
    ) 
    user.save!  #Error message said this line is problem 
end 
相關問題