【问题标题】:Checking Expense amount and expense type maximum cap检查费用金额和费用类型最大上限
【发布时间】:2014-08-18 11:49:51
【问题描述】:

我正在尝试使用 Rails 4.1 构建一个小型费用跟踪应用程序。有一个带有费用名称和上限的费用类型模型。这用于设置 Gas、Mobile 等索赔的最大上限。费用类型属于用户提交的费用模型。在新的费用表单中,他们可以从下拉列表中选择费用类型并添加行项目。

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

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

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 

想知道如何正确使用费用类型ID来检查条件有人可以帮我吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您的费用类型关联是倒退的。费用应该属于费用类型,而不是相反。

    使用 ActiveRecord 验证和错误来表明金额超过上限。这样记录将无效,直到有效才会保存。

    检查费用金额是否大于上限。只要费用金额高于或低于上限,检查它是否不相等就会将该项目标记为超出预算。

    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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多