Correct rails validation after editing field value

Basically, I have a user model that has a quantity and a money field. When I first create a user, I confirm that user.amount <= user.money. However, the user is allowed to change the amount through “editing”. In the update action, when the user changes the amount, I calculate the difference between old and new (old minus new) amounts through

  amount_change = user.amount - params[:user][:amount].to_f

I don’t know if this is a good form, but it works for me. Basically, I do not save the difference and calculate it only as the user tries to change the amount. In any case, when the user edits, I would like to confirm this amount_change <= user.money. How can i do this? I feel that I need to pass something in confirmation, but I don’t know how I can go in amount_change, since it is calculated in the middle of the update method of my user controller. Many thanks!

+5
source share
1 answer

You can use ActiveModel :: Dirty to access the old value (like 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
+11
source

All Articles