开发者

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'])

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜