2013-10-01 162 views
0

有人可以幫我理解下面的代碼。當您產生activerecord對象時會發生什麼?

def self.with_optimistic_lock(attrs) 
    begin 
    payment = where(attrs).first_or_create 
    yield(payment) 
    payment.save! 
    rescue ActiveRecord::StaleObjectError, ActiveRecord::StatementInvalid, ActiveRecord::RecordInvalid => e 
    retry 
    end 
end 

其中attrs是散列參數。 Post是繼承自ActiveRecord::Base的類。

這是https://github.com/fantgeass/rails-test-tasks/blob/master/app/models/payment.rb

+0

沒有什麼不尋常情況。一如往常。 –

回答

1

它產生的,就像任何其他塊將,使得提供給塊產生對象的代碼片段:

Post.with_optimistic_lock(:name => "Foo") do |post| 
    # The 'post' variable contains the ActiveRecord object yielded from the method 

    # Once this block ends, the method will resume at the `payment.save!` line 
end 
+0

你能解釋一下它將如何恢復到payment.save!? – Zahid

+0

'with_optimistic_lock'內的'yield'調用塊直到調用塊完成,然後一旦該塊被執行,'with_optimistic_lock'方法繼續。您可以閱讀http://www.tutorialspoint.com/ruby/ruby_blocks.htm瞭解阻塞/屈服如何工作的概述。 –

+0

很好的回覆.... – Zahid

相關問題