有人可以帮我理解下面的代码。
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