使用自定义方法验证并向错误添加消息

时间:2014-09-14 20:36:33

标签: ruby-on-rails ruby-on-rails-4

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

我的数据只是零,但如果我尝试保存它,我就不会收到任何错误消息,并且新记录开始保存。我哪里错了?

1 个答案:

答案 0 :(得分:1)

您需要将before_save替换为validate

validate :check_validity
相关问题