2010-12-23 68 views
5

基本上我有一个用户模型,有一个金额和金钱领域。当我第一次创建用户时,我验证user.amount <= user.money。但是,用户可以通过“编辑”更改金额。在更新操作,当用户改变量,我计算通过rails编辑字段值后自定义验证

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

新旧(减去新老)金额的差额,我不知道这是很好的形式,但它为我工作。基本上我没有储存差异,只是在用户试图改变金额时才计算它。无论如何,当用户编辑,我想验证amount_change <= user.money而不是。我怎样才能做到这一点?我觉得我应该通过一些验证,但我不知道我怎么能通过amount_change,因为它是在我的用户控制器的更新方法的中间计算的。 非常感谢!

回答

11

您可以使用ActiveModel::Dirty访问旧值(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 
+0

这似乎排序的工作 - 有,如果它没有通过验证的首次尝试错误,但如果用户只需再次点击提交,就没有错误......是因为新的金额_数量和金额已设置?谢谢! (也是_changed内置的?) – butterywombat 2010-12-23 01:51:24