2011-02-26 29 views
0

我想寫一段代碼,使其保證在任何時候,只有一個進程可以更新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
class Post 

    @@activation_lock = Mutex.new 

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

end 
相關問題