mercredi 4 janvier 2017

Rails 3 find_or_create_by_slug sometimes creates duplicate records

I am using Rails 3.2.14 with Ruby 2.1.0. I have a method which takes care of creating a user in DB by checking if the email id exists or not.

I use devise and SAML for user authentication and session creation.

I use the following code to do so:

@user = User.find_or_create_by_email(:email=>"xyz@gmail.com", firstname: 'XY', lastname: 'Z', code: 'ABC')

This works in most of the cases, but rest of the time I keep getting error notification emails in my account as the above code tries to create one more user with the same email:

An ActiveRecord::RecordNotUnique occurred in sessions#consume:

  Mysql2::Error: Duplicate entry 'xyz@gmail.com' for key 'email'

How I can avoid this error?

Aucun commentaire:

Enregistrer un commentaire