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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With