【问题标题】:Force update ActiveRecord association强制更新 ActiveRecord 关联
【发布时间】:2012-10-01 16:48:42
【问题描述】:

我有一个自引用循环,它引用最近的关联记录以查看它是否被赶上。但是,它一直在引用第一个关联的记录,因此它一直处于无限循环中。我认为这是因为 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

【问题讨论】:

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


    【解决方案1】:

    你可以试试

    Model.association(force_reload=true)
    

    参考here(也适用于有很多关系)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多