Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate Records created by find_or_create In Rails+Mongoid

I have an object Message which is only ever created by this line:

Message.find_or_create_by(:api_id => params['message_id'])

In theory, I should never have two messages with the same api_id, but... I do. It happens when two requests happen simultaneously that both call that line.

Someone else has posted the same problem with ActiveRecord: Duplicate Records created by find_or_create_by_ But I am using Mongoid.

How do I go about solving this?

like image 352
tybro0103 Avatar asked Sep 20 '11 16:09

tybro0103


1 Answers

Found a solution using upserts:

Message.collection.update({:api_id => params['message_id']}, {'$set' => {:api_id => params['message_id']}}, :upsert => true)
@message = Message.where(:api_id => params['message_id']).first

Feels a little messy, but works. Still open to alternatives.

like image 196
tybro0103 Avatar answered Sep 16 '22 18:09

tybro0103