views:

45

answers:

2
class Account < ActiveRecord::Base
  after_update :give_user_credit, :on => :update 

  def give_user_credit
    credit = User.current_user.credit + 3.8
    User.current_user.update_attribute(:credit, credit)
  end
end

When I use this the server hangs and when I come back to the application after a full reboot my credit is in the £1000's.

Whats going on here..

Thanks :D

+6  A: 

Looks to me like you are setting the :give_user_credit callback to run every time that the record is updated.

But since the callback updates the record, it then triggers the callback again, which will continue on and on...

ewall
Thanks for that ive moved the logic into the controller and now its working fine, shame the £3112.20 is fake :P
Karl Entwistle
@Karl How about before_save :on => :update and then just don't call update_attribute...?
hurikhan77
+1  A: 

You could also use this private method:

model.credit = 10
model.send(:update_without_callbacks)
Tanel Suurhans