0

I used omniauth-kakao gem to login through SNS.

Then I succeed to login and I got token and profile of SNS.

But when the other user(not me) has signed up through SNS, I met the error

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

And this is code in app/model/user.rb that makes the error

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

Also, I made two model. User.rb and Identity.rb.(Identity.rb refer User.rb)

Identity.rb has 'Provider(sns)', 'User' column. User.rb has user's information, profile of SNS column.

When error occur, row was added to Identity.rb and this row has not user_id in 'User' column.(Others was added, only user_id was not added)

In addition, row was not added to User.rb never

What's the problem??

Asdrubal
  • 2,421
  • 4
  • 29
  • 37
CHOIHEEJAE
  • 11
  • 3
  • https://stackoverflow.com/questions/18496223/possible-to-specify-unique-index-with-nulls-allowed-in-rails-activerecord – m3characters Jul 28 '17 at 18:40

1 Answers1

0

Should you not be saving email with user in db in below code:

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

It should be like:

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
Vijay Agrawal
  • 1,643
  • 12
  • 17