开发者

Duplicate Records created by find_or_create In Rails+Mongoid

开发者 https://www.devze.com 2023-04-06 09:21 出处:网络
I have an object Message which is only ever created by this line: Message.find_or_create_by(:api_id => params[\'message_id\'])

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

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

开发者_如何学JAVAIn 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号