rails - 实现一个简单的锁,以防止用户同时编辑相同的数据

sa1*_*125 4 concurrency mutex locking ruby-on-rails

我有一个应用程序,我需要阻止用户在由其他用户编辑数据时编辑数据.我正在考虑最好的方法,并想要提出想法.到目前为止,我已经创建了一个设置模型,可以在键/值对中存储db上的应用程序范围配置.所以,对于锁,我有一个名为LOCKED_TABLE_UID的设置实例,它存储了编辑表的用户的user_id,如果表是空的,则为null(nil).

>> lock = Setting.find_by_key('LOCKED_TABLE_UID')
Run Code Online (Sandbox Code Playgroud)

然后,我在我的应用程序控制器中实现了2个方法来获取和释放锁:

# current_user returns the user currently logged in
def acquire_lock
  lock = Setting.find_by_key("LOCKED_TABLE_UID")
  if lock.value
    # if lock taken, see if it's the current_user or someone else
    if lock.value.to_i == current_user.id.to_i
      return true
    else
      return false
    end
  else
    # lock is free, assign it to this user
    lock.value = current_user.id
    return true if lock.save
  end
end

def release_lock
  lock = Setting.find_by_key("LOCKED_TABLE_UID")
  if lock.value
    # the lock belongs to current_user, so he can release it
    if lock.value.to_i == current_user.id.to_i
      lock.value = nil
      return true if lock.save
    else
      # not your lock, go away
      return false
    end
  else
    # lock is free, quit bugging
    return true
  end
end
Run Code Online (Sandbox Code Playgroud)

我想要的是创建一些包含锁定机制的块代码,如下所示:

def some_crud_action
  requires_locking do |lock|
    if lock
      # do some CRUD stuff here
    else
      # decline CRUD and give some error
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我很感激这方面的帮助 - 但我也对如何完成所有这些,或者我可能忽略的一些事情持开放态度.这个锁不一定是原子的,但是相当基本且最重要 - 它有效:)谢谢.

Sim*_*tti 7

你见过ActiveRecord内置锁定功能吗?


EmF*_*mFi 1

你快到了。创建您的 require_locking?采取您认为合适的行动。然后用 before_filter 对其进行处理。

 before_filter :requires_locking?, :only => [:update, :destroy]
 after_filter :release_lock, :only => [:update, :destroy]

 def requires_locking do |lock|
   unless acquire_lock
      lock = Setting.find_by_key("LOCKED_TABLE_UID")
      user_with_lock = User.find(lock.value)
      flash[:message] = "Action denied: Table locked by: #{user_with_lock.name}"
      redirect_to :back
   end
 end
Run Code Online (Sandbox Code Playgroud)