I'm having a hard time w/ the after_update callback on rails... As
far as I can tell, when I define a after_update callback on a model,
the attributes of the object have the same values that they had
*before* Base.save was called. I'm probably wrong so here's the code:
transaction.destroy
assert_equal -100.00, account.balance #this assertion will pass
end
FAILURE OUTPUT:
Loaded suite test/unit/register_item_test
Started
.F.
Finished in 0.202591 seconds.
1) Failure:
test_register_item_adjusts_account_balance(RegisterItemTest)
[test/unit/register_item_test.rb:31]:
<-115.5> expected but was
<-113.44>.
3 tests, 6 assertions, 1 failures, 0 errors
So changing the amount on a transaction (RegisterItem) should change
the current balance of an account. Here's the relevent callbacks:
REGISTER_ITEM UPDATE CALLBACKS:
def before_update
account.balance -= amount
account.save
end
def after_update
account.balance += amount
account.save
end
So the idea is that before the transaction is updated i subtract the
amount of the transaction back from the account, and then add the new
amount back on. It looks like @amount is still the old value during
the after_update callback though. is that correct? how can i access
the new value?
so you're back where you started, which is what your test is telling you.
Ok so there is a problem in the way i understand the before_update
callback, or in your logic (probably my problem which would explain
the bug). Anyway, this is a before/after_*update* callback, it looks
like the scenario you're describing is a before/after_*create* kind of
deal. so the way i would understand it would be like so:
Would calling account.reload after the save cause problems for you
elsewhere?
I wasn't aware of the reload method. I called it after save and
although it didn't cause any problems, it didn't change the behavior
of the program either (unless i called self.reload on the transaction,
in which case it looks like the after_update callback didn't get
called)
it makes sense... i hadn't understood how it worked previously. i
figured that since it was before save was called, that the data would
have been the old data. so is there no way to access the previous
data w/ callbacks? i guess i could store the old amount in all of the
RegisterItem model, but i'd rather not go that route.