强制更新ActiveRecord关联

时间:2012-10-11 04:58:30

标签: ruby-on-rails ruby database ruby-on-rails-3 activerecord

我有一个自引用循环,引用最近的相关记录以查看它是否被捕获。但是,它会不断引用第一个关联的记录,因此它会继续进行无限循环。我认为这是因为ActiveRecord事务在整个循环中保持运行,因此它永远不会停止并自行更新。

有没有办法强制模型在继续之前重置自己?

这是我的模型(不是异常提升,所以我可以验证我们是否真的进入下一个记录)。

class RecurringRule < ActiveRecord::Base
  belongs_to :organization
  has_one :last_run, :class_name => "Transaction", :order => 'id DESC'
  has_many :transactions

  attr_accessible :period, :last_run_id

  after_create :destroy_if_period_empty

  def destroy_if_period_empty
    if !period?
      self.destroy
    end
  end

  def recur
    @count = @count || 0
    if @count > 0 then raise last_run.id.to_s end
    if last_run.created_at.to_date.advance(period.pluralize.to_sym => 1) >= Date.today 
      new = Transaction.new({
        amount: last_run.amount,
        person_id: last_run.person_id,
        organization_id: last_run.organization_id,
        recurring_rule_id: last_run.recurring_rule_id
      })
      new.save!
      @count += 1
      self.recur
    end
    return @count
  end
end

1 个答案:

答案 0 :(得分:1)

你可以尝试

Model.association(force_reload=true)

请参阅here以供参考(它也适用于许多关系)