当你产生一个activerecord对象时会发生什么?

时间:2013-10-01 14:35:43

标签: ruby-on-rails-3

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

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

的代码段

1 个答案:

答案 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