轨道迁移:检查变量是否存在



我正在做一个新的rails迁移文件,将属性内容从模型移动到另一个模型:

class StepIdCorrectionForReportSheetTemplate < ActiveRecord::Migration[5.1]
  def change
      Report.current.find_each do |report|
        first_sheet = report.sheets.select{ |sheet| !sheet.is_archived }.sort_by{ |sheet| sheet[:order] }.first
        if not report.step_id.nil?
          first_sheet.update( step_id: report.step_id )
          first_sheet.template.update( step_id: report.step_id )
        end
    end
  end
end

我收到此错误:

未定义的方法"更新" nil:nilClass /home/sahnoun/altagem/web/db/migrate/20190208104955_step_id_correction_for_report_sheet_template.rb:7:in "阻止更改">

我想我应该添加一些其他测试来检查是否存在report_sheetreport_sheet.template

是的,您可以检查是否存在first_sheet.template

 first_sheet.template.update( step_id: report.step_id ) if first_sheet.template

最新更新