Skip to content

Instantly share code, notes, and snippets.

@ilake
Created October 3, 2013 02:04
Show Gist options
  • Save ilake/6803569 to your computer and use it in GitHub Desktop.
Save ilake/6803569 to your computer and use it in GitHub Desktop.

Please note this method is not atomic, it runs first a SELECT, and if there are no results an INSERT is attempted. If there are other threads or processes there is a race condition between both calls and it could be the case that you end up with two similar records.

Whether that is a problem or not depends on the logic of the application, but in the particular case in which rows have a UNIQUE constraint an exception may be raised, just retry:

begin
  CreditAccount.find_or_create_by(user_id: user.id)
rescue ActiveRecord::RecordNotUnique
  retry
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment