本文介绍了轨道3 - 潜在的竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的Rails 3应用程序,用户可以保留的某一天同质项目的数量有限的。我试图避免出现竞争状况,其中两个人保留的最后一个项目可以在特定的一天。该模型(简化)如下:

I have a really simple Rails 3 application where users can reserve one of a finite number of homogeneous items for a particular day. I'm trying to avoid a race condition where two people reserve the last item available on a particular day. The model (simplified) is as follows:

class Reservation < ActiveRecord::Base
  belongs_to :user
  attr_accessible :date
  MAX_THINGS_AVAILABLE = 20

  validate :check_things_available

  def check_things_available
    unless things_available? errors[:base] << "No things available"
  end

  def things_available?
    Reservation.find_all_by_date(date).count < MAX_THINGS_AVAILABLE
  end
end

预约正在在控制器通过创建current_user.reservations.build(PARAMS [:预订])

感觉就像有一种更好的方式来做到这一点,但我不能完全把我的手指上的是什么。如何prevent任何帮助的竞争条件将大大AP preciated。

It feels like there is a better way to do this, but I can't quite put my finger on what it is. Any help on how to prevent the race condition would be greatly appreciated.

推荐答案

只要使用任何锁定机制,如 Redis的更衣室

Just use any locking mechanism like redis locker

RedisLocker.new("thing_to_sell_#{@thing.id}").run do
  current_user.create_reservation(@thing) or raise "Item already sold to another user"
end

这篇关于轨道3 - 潜在的竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 22:47