我试图强制在我的表字段之一的值的唯一性。更改表格不是一个选项。我需要使用ActiveRecord有条件地插入一行到表中,但我关心同步。Rails的竞争条件first_or_create
是否first_or_create
在Rails ActiveRecord中预防竞争状态?
这是从GitHub的first_or_create
的源代码:
def first_or_create(attributes = nil, options = {}, &block)
first || create(attributes, options, &block)
end
是否有可能重复的条目将导致数据库由于有多个进程同步的问题?
AR充满了这样的竞争条件。 – dbenhur
请参阅(SO dup)[我如何避免Rails应用程序中的竞态条件?](http://stackoverflow.com/questions/3037029/how-do-i-avoid-a-race-condition-in-my -rails-app)和Rails Cookbook [避免使用乐观锁定的竞态条件](http://underpop.free.fr/r/ruby-on-rails/cookbook/I_0596527314_CHP_3_SECT_19.html) – dbenhur
@dbenhur - 我无法使用乐观锁定,因为它涉及到向表中添加一个字段。我的一个条件是我不能添加一个字段,所以它不是重复的。 –