首页 > 解决方案 > EnvelopesController#index 中的参数错误

问题描述

我正在尝试验证帐户中的金额不能小于信封中的金额之和,但我收到此错误

您需要提供至少一项验证验证:total_amount_in_all_envelope_can_not_be_greater_than_account_total在此处输入图像描述

这是我的模型

class Envelope < ApplicationRecord
  belongs_to :account

    validates :tag, presence: true
    validates :account_id, presence: true
    validates :amount, presence: true, numericality: {greater_than: 0, message: " must be greater than $0.0 "}  
    validates :total_amount_in_all_envelope_can_not_be_greater_than_account_total


    def total_amount_in_all_envelope_can_not_be_greater_than_account_total
        if 
            @account.envelopes.sum(&:amount) > @account.amount
            errors.add(:amount, "Envelope amount cannot be reater than Account total" )
        end
    end
end

标签: rubyruby-on-rails-5

解决方案


使用自己的方法填充记录errors时,调用的方法是validate,而不是validates

validate :total_amount_in_all_envelope_can_not_be_greater_than_account_total

推荐阅读