【发布时间】:2013-04-28 18:39:48
【问题描述】:
我的付款模式如下:
class Payment < ActiveRecord::Base
attr_accessible :amount, :method, :payment_date, :reference_no, :invoice_id
belongs_to :invoice
validates :amount, presence: true
validates :method, presence: true
validates :payment_date, presence: true
validate :payment_not_more_than_balance
def payment_not_more_than_balance
if amount > self.invoice.balance
self.errors.add :amount, 'Payments should be less than or equal to the Invoice amount'
end
end
end
我正在尝试运行验证,一旦有人尝试支付超过发票余额的款项,就会发出验证错误。
目前,上面的代码向数据库提交然后运行验证。
也就是说,如果我的发票余额为 2000,当我支付 2000 时,付款已提交(留下发票余额为 0),然后我收到错误“付款应该是小于或等于发票金额',这是不必要的。
如果我在发票余额为 0 时尝试再次支付 2000 美元,则会出现该错误
我该如何纠正?
【问题讨论】:
-
你可以做一个 before_validation 钩子。 before_validation :your_validation
-
我做了一个 before_validation 钩子,问题仍然存在,先保存然后运行验证
-
我认为 before_save 是您所需要的,但请确保它返回 false 以防止保存!
标签: ruby-on-rails ruby ruby-on-rails-3 validation