2011-02-26 3 views
0

保証というコードを書くと、いつでも1つのプロセスだけが投稿テーブルの特定のレコードのフィールドを更新できます。テーブル内のフィールドを更新する際のアトミック性を確保する方法は?

これは正しい方法ですか?

#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 
関連する問題