模型计算失败的rake任务

时间:2016-03-06 11:56:01

标签: ruby-on-rails ruby model rake-task

我在我的模型中设置了一个方法/操作/一段代码(我总是对rails术语有点遗失),以便在我输入新广告时更新预算中的剩余金额。

class Budget < ActiveRecord::Base
belongs_to :client
has_many :adverts
before_save :update_budget

validates :name, :amount, :client_id, presence: true

def update_budget
    self.amount_remaining = self.amount - self.amount_spent
end
end

在更新预算或输入新广告时,此功能正常。一切都按预期工作。但是,我已经编写了一个rake任务来将经常性预算列表写入预算表(因此我可以按月安排)。但是,当我从终端运行此任务时,它会遇到错误。

rake任务。

desc "Recurring Updates"
task :recurring_budgets => :environment do
    @recurring_budgets = RecurringBudget.all
    @recurring_budgets.each do |recurring_budget|
        Budget.create(name: recurring_budget.name, amount: recurring_budget.amount, client_id: recurring_budget.client_id)
    end
end

错误。

$ rake recurring_budgets
rake aborted!
TypeError: nil can't be coerced into Fixnum
/Users/tomgamon/projects/adsman/app/models/budget.rb:9:in `-'
/Users/tomgamon/projects/adsman/app/models/budget.rb:9:in `update_budget'
/Users/tomgamon/projects/adsman/lib/tasks/recurring_budgets.rake:6:in `block (2 levels) in <top (required)>'
/Users/tomgamon/projects/adsman/lib/tasks/recurring_budgets.rake:5:in `block in <top (required)>'
Tasks: TOP => recurring_budgets
(See full trace by running task with --trace)

值得注意的是,当我从模型中删除方法时,任务会很好地写入预算表。

有人有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是因为您试图从minus

尝试nil amountupdate_budget中调用了

before_save callback - 在此计算amount_remaining,在您的案例amount_spent中从amount减去amount_spent为{{1} },所以当你尝试从某个东西中减去nil值时,你会收到此错误 - nil

有两个解决方案 -

1 - 如果TypeError: nil can't be coerced into Fixnumamount_spent,您必须使用nil

0

2 - 您可以在迁移中将def update_budget self.amount_remaining = self.amount - (self.amount_spent || 0) end amount_remainingamount的默认值设置为amount_spent(零)。

最好为此类字段设置默认值,而不是检查代码中的0值。