我正在尝试使用Rails 4.1构建一个小的费用跟踪应用程序。有一个expense_types模型,它包含了expense_name和cap。这是用来为气体,移动等索赔设定上限。费用类型属于用户提交的费用模型。在新的支出表单中,他们可以从下拉列表中选择支出类型,并添加行项。
我使用一个模型方法来计算所有行项的总数。现在,我想检查每一次提交后,总金额是否超过费用类型上限。每次提交的费用类型都会被存储。例如,如果一个天然气(expense_type_id = 2)账单是100美元,上限是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来检查情况,有人能帮我吗?
发布于 2014-08-18 16:35:27
您的expense_type关联是反向的。开支应该是belong_to 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
endhttps://stackoverflow.com/questions/25362633
复制相似问题