basically I have a user model that has an amount and money field. When I first create the user, I validate that user.amount <= user.money
. However, the user is allowed to change the amount via 'edit'. In the update action, when the user changes the amount, I calculate the difference between the old and new (old minus new) amounts via
amount_change = user.amount - params[:user][:amount].to_f
I don't know if this is good form but it works for me. Basically I'm not storing the difference and calculating it only as the user is trying to change the amount. Anyway when the user edits, I would like to validate that amount_change <= user.money
instead. How can I do this? I feel like I should be passing something to the validation, but I don't know how I can pass in amount_change
since it's calculated in the middle of the update method of my users controller.
Thanks so much!
You can use ActiveModel::Dirty to access the old value (as amount_was
):
class User < ActiveRecord::Base
# ...
validate :ensure_amount_change_less_than_money,
:on => :update,
:if => :amount_changed?
def ensure_amount_change_less_than_money
if (self.amount - self.amount_was) <= self.money
errors.add(:money, 'Amount change must be less than money')
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With