Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails custom validation after editing a field's value

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!

like image 506
butterywombat Avatar asked Dec 23 '10 01:12

butterywombat


1 Answers

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
like image 132
bowsersenior Avatar answered Nov 09 '22 11:11

bowsersenior