1

我在 Rails 模型上使用乐观锁定。在循环内部,我更新并保存了这个模型(或者,更确切地说,这个模型的许多实例)。

从循环内部,我输出“之前”和“之后”值,并且该字段似乎已正确更新。但是之后,当我通过 ID 找到模型时,我看到该字段没有更新。谁能发现我的错误?

class Usage::LeadDistributionWeight < ActiveRecord::Base
  attr_accessible :agent_id, :tag_value_id, :weight, :premium_limit, :countdown, :lock_version, :tag_value

  def increment_countdown!
    self.countdown = self.countdown + self.weight
    save
  rescue ActiveRecord::StaleObjectError
    attempts_to_crement_countdown ||= 0
    attempts_to_crement_countdown += 1
    self.increment_countdown! unless attempts_to_crement_countdown > 5
    false
  end

  def self.increment_countdowns parent_id, lead_type_id
    if lead_type_id.present?
      joins(:agent)
      .where("#{reflect_on_association(:agent).table_name}.parent_id = ?", parent_id)
      .where(tag_value_id:lead_type_id)
      .all(readonly:false).each { |weight|
        prev = weight.countdown
        if weight.increment_countdown!
          puts "#{prev} differs from #{weight.countdown}"
        else
          puts "no difference!"
        end
      }
    end
  end
end
4

0 回答 0