如何在特定时间内锁定Rails 3中的记录?

时间:2011-10-13 03:09:33

标签: ruby-on-rails-3 rails-postgresql pessimistic-locking

我想要做的是基本上让用户获取记录上的锁定并将其保留一段特定的时间,以便他们可以对其进行更改,例如维基百科。因此,假设维基百科文章为用户提供了一小时的时间来编辑它,然后其他用户就可以对其进行编辑。

如何使用Rails 3实现这一目标?我已经阅读并发现悲观锁定是我应该用于锁定的。鉴于......一小时后我会用什么样的机制释放锁?

我的堆栈是Rails 3,Heroku,PostgreSQL。

感谢您提供任何答案,我很乐意看到代码,如果可以,那就太棒了!

3 个答案:

答案 0 :(得分:0)

这是一个创建锁的示例,但不删除它们。

我把它留给你。

在此示例中,锁定会在一小时后过期,但要完成应用程序,应在成功更新帖子时自动删除它们。

working example

或阅读

relevant commit

答案 1 :(得分:0)

您可以使用acts_as_lockable_by宝石来做到这一点。

想象一下,您有一个只能由一个用户编辑的耐心(ActiveRecord)类,并且应该将该用户锁定,直到他决定释放该类:

class Patient < ApplicationRecord
  acts_as_lockable_by :id, ttl: 30.seconds
end

然后您可以在控制器中执行此操作:

class PatientsController < ApplicationController
  def edit
    if patient.lock(current_user.id) 
      # It will be locked for 30 seconds for the current user
      # You will need to renew the lock by calling /patients/:id/renew_lock
    else
      # Could not lock the patient record which means it is already locked by another user
    end
  end

  def renew_lock
    if patient.renew_lock(current_user.id)
      # lock renewed return 200
    else
      # could not renew the lock, it might be already released
    end
  end

  private

  def patient
    @patient ||= Patient.find(params[:id])
  end
end

答案 2 :(得分:-1)

添加名为“editable_until”的字段:datetime并在创建记录时设置特定日期(Time.now + 30.min f.e.)。只需查询此字段即可确定用户是否有权更新记录。

class Post << AR
  before_validation :set_editable_time

  validate :is_editable

  def editable?
    self.editable_until.nil? || self.editable_until >= Time.now
  end

protected
  def is_editable
    self.errors[:editable_until] << "cannot be edited anymore" unless editable?
  end

  def set_editable_time
    self.editable_until ||= Time.now + 30.min
  end
end

Post.create(:params....)
=> <Post, ID:1, :editable_until => "2011-10-13 15:00:00">

Post.first.editable?
=> true

sleep 1.hour

Post.first.editable?
=> false