I have a self-referencing loop that references the most recent associated record to see if it’s caught up. However, it keeps referencing the first associated record, so it keeps going in an infinite loop. I think this is because the ActiveRecord transaction keeps running throughout the loop, so it never stops and updates itself.
Is there any way to force a model to reset itself before continuing on?
Here’s my model (not that the exception raising is just so I can verify whether we’ve actually advanced to the next record).
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
You can try
See here for reference (it is valid also for has many relations)