竞态条件在Rails的first_or_create [英] Race conditions in Rails first_or_create

查看:84
本文介绍了竞态条件在Rails的first_or_create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图强制执行值的唯一性在我的表中的字段之一。改变表不是一个选项。我需要使用ActiveRecord有条件行插入表中,但我很担心同步。

I'm trying to enforce uniqueness of values in one of my table fields. Changing the table isn't an option. I need to use ActiveRecord to conditionally insert a row into the table but I'm concerned about synchronization.

确实 first_or_create 在Rails的ActiveRecord的prevent竞争条件?

Does first_or_create in Rails ActiveRecord prevent race conditions?

这是源$ C ​​$下 first_or_create 从GitHub的:

This is the source code for first_or_create from GitHub:

def first_or_create(attributes = nil, options = {}, &block)
  first || create(attributes, options, &block)
end

是否有可能重复的条目将导致数据库由于有多个进程同步的问题?

Is it possible that a duplicate entry will result in the database due to synchronization issues with multiple processes?

推荐答案

是的,这是可能的。

您可以显著减少冲突与任何乐观或有机会悲观锁定。当然,乐观锁需要增加一个字段的表,悲观锁不能扩展,以及 - 加,这取决于你的数据存储的能力。

You can significantly reduce the chance of conflict with either optimistic or pessimistic locking. Of course optimistic locking requires adding a field to the table, and pessimistic locking doesn't scale as well--plus, it depends on your data store's capabilities.

我不知道你是否需要额外的保护,但它的使用。

I'm not sure whether you need the extra protection, but it's available.

这篇关于竞态条件在Rails的first_or_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆