0

有人可以帮我理解下面的代码。

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的代码片段

4

1 回答 1

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
于 2013-10-01T14:40:46.703 回答