使用ActiveRecord在特定时间保留一行

时间:2011-12-28 07:12:01

标签: ruby-on-rails activerecord transactions locking

我希望能够“保留”类似于飞机座位在实际支付之前短时间锁定的元素。我认为最好的方法是通过数据库,最好是在ORM层。

以下是一个例子:

ActiveRecord::Base.transaction do
  bar = Bar.find(1, :lock => true)
  # do my stuff
end

我需要一个更灵活的解决方案。

以下是我想象它在概念上的运作方式:

# action1: 
# put an expiring lock (30s) on an element (don't block unrelated code) 
# other code

# action2 (after payment):
# come back to the locked element to claim ownership of it

更新:任何尝试在Rails中执行此操作的人都应首先尝试使用built-in optimistic locking功能。

2 个答案:

答案 0 :(得分:2)

添加一个额外的列locked_until - 但要注意并发性。我可能会在db层上做到这一点。

答案 1 :(得分:0)

我可以为此目的专门设一个名为potential_owner的表。它会有一个时间戳,以便人们可以计算出时间。基本上它会起作用:

# lock the table
# check latest record to see if the element is available
# add a new record or die

这很容易实现,但锁定并不精细。该表描述了不同元素的潜在所有权,并且简单的检查锁定了整个表。在Tass的解决方案中,只锁定特定元素的行。