Question: Rails 3 find_or_create_by_slug sometimes creates duplicate records


Rails 3 find_or_create_by_slug sometimes creates duplicate records

Answers 1
Added at 2017-01-04 10:01

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=>"", 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 '' for key 'email'

How I can avoid this error?

nr: #1 dodano: 2017-01-04 10:01

You need to use something like Upsert

find_or_create will first run SELECT and then INSERT. Another instance could have run the INSERT in between. You could also maybe use a transaction:

User.transaction do 
  @user = User.find_or_create_by_email(:email=>"", firstname: 'XY', lastname: 'Z', code: 'ABC')
Source Show
◀ Wstecz