检查费用金额和费用类型最大上限

时间:2014-08-18 11:49:52

标签: ruby-on-rails

我正在尝试使用Rails 4.1构建一个小费用跟踪应用。有一个expense_types模型,其中包含expense_name和cap。这用于设置Gas,Mobile等声明的最大上限。费用类型属于用户提交的费用模型。在新的费用表单中,他们可以从下拉列表中选择费用类型并添加订单项。

我使用模型方法计算所有订单项的总和。现在,如果总金额超过费用类型上限,我想在每次提交后检查。为每次提交存储费用类型。例如,如果以$ 100提交Gas(expense_type_id = 2)帐单并且上限为$ 80,我想更新通知属性。

我有点困惑如何正确地做到这一点。我尝试了以下方法,但得到了未定义的方法expense_type错误:

def check_cap
    if self.expense_amount.to_i != self.expense_type.cap
        self.update_attribute(:notification, "This item is over the budget")
    end
end 

想知道如何正确使用expense_type_id检查情况有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您的expense_type关联是向后的。费用应该属于expense_type,而不是相反。

使用ActiveRecord验证和错误来指示金额超过上限。这样,记录无效,在有效之前不会保存。

检查expense_amount是否大于上限。检查它是否相等会在费用金额高于或低于上限时将该项目标记为超出预算。

class ExpenseType < ActiveRecord::Base
  has_many :expenses
end

class Expense < ActiveRecord::Base
  belongs_to :expense_type

  validate :expense_amount_is_within_cap

  def expense_amount_is_within_cap 
    if expense_amount > expense_type.cap
      errors.add(:expense_amount, 'is over the budget')
    end
  end
end