如何在更新表中的字段时确保原子性?

时间:2011-02-26 06:49:42

标签: ruby-on-rails ruby-on-rails-3

我想编写一段代码,以便保证在任何时候,只有一个进程可以更新posts表中某个记录的字段。

这是正确的方法吗?

#Make a check before entering transaction, so that a transaction
#is not entered into needlessly (this check is just for avoiding
#using DB resources that will be used when starting a transaction)    

if @post.can_set_to_active?

  ActiveRecord::Base.transaction do

    #Make a check again, this time after entering transaction, to be 
    #sure that post can be marked active.

    #Expectation is that inside a transaction, it is guaranteed that no other
    #process can set the status of this post.

    if @post.can_set_to_active?
      #now set the post to active
      @post.status = :active
      @post.save
    end #end of check inside transaction

  end #end of transaction

end #end of check outside transaction

另外,有没有办法使用RSpec甚至其他方法测试这个场景?

1 个答案:

答案 0 :(得分:1)

class Post

  @@activation_lock = Mutex.new

  def activate
    self.status = :active
    self.save
  end
  synchronize :activate, :with => :@@activation_lock

end