0

我一生都无法弄清楚为什么会崩溃。我已经阅读了大量关于 stackoverflow 和谷歌搜索的指南,他们都说了同样的话,这就是我正在做的事情。

这是代码:

current_schedule_record['next_oil_change'] = Maintenance.where("vehicle_id = ? AND maintenance_type = ?", id, 'oil change').select("kilometres").order('kilometres DESC').first.kilometres
if current_schedule_record['next_oil_change'].blank?
    current_schedule_record['next_oil_change'] = current_schedule_record['next_oil_change']
else
    current_schedule_record['next_oil_change'] = nil
end

基本上我正在尝试检查该记录是否存在并将其吐回,如果它不返回零。

我得到的错误是:undefined method 'kilometres' for nil:NilClass

4

1 回答 1

1

你可以尝试一个小的重构:

maintenance = Maintenance.where("vehicle_id = ? AND maintenance_type = ?", id, 'oil change').select("kilometres").order('kilometres DESC').first

current_schedule_record['next_oil_change'] = maintenance.nil? ? nil : maintenance.kilometres

if current_schedule_record['next_oil_change'].blank?
  current_schedule_record['next_oil_change'] = current_schedule_record['next_oil_change']
else
  current_schedule_record['next_oil_change'] = nil
end

编辑:

您没有做错任何事情,您的维护查询没有返回任何结果,这些结果将自动实例化为返回的第一个维护对象 ( .first)。

由于没有结果,因此该方法将在针对对象.kilometres执行时失败。nil

您需要显式检查是否有返回的对象,然后执行该.kilometres方法。

另一种选择是try方法:

current_schedule_record['next_oil_change'] = Maintenance.where("vehicle_id = ? AND maintenance_type = ?", id, 'oil change').select("kilometres").order('kilometres DESC').first.try(:kilometres)

if current_schedule_record['next_oil_change'].blank? # Might want a .nil? check here instead.
  current_schedule_record['next_oil_change'] = current_schedule_record['next_oil_change']
else
  current_schedule_record['next_oil_change'] = nil
end
于 2013-08-06T16:42:13.473 回答