class Confirmation < ActiveRecord::Base
before_save :check_validity
def check_validity
case target
when 'statements'
statements = Statement.where(user: user, date: [start_date..end_date])
total_earnings = statements.to_a.sum(&:earning)
total_expenses = statements.to_a.sum(&:expense)
unless total_earnings > 0
errors.add(:earning, "Earning must be positive")
end
unless total_expenses > 0
errors.add(:expense, "Expense must be positive")
end
end
end
我的数据只是零,但如果我尝试保存它,我就不会收到任何错误消息,并且新记录开始保存。我哪里错了?
答案 0 :(得分:1)
您需要将before_save
替换为validate
validate :check_validity