0
votes

I am running a rails migration where for all records, I want to set the value of a new column 'result' based on the value of an existing column - 'score'.

class AddResultToReports < ActiveRecord::Migration
  def change
    add_column :reports, :result, :integer
    Report.all.each do |r|
      r.update_attribute(:result, 0) if (r.score < 40)
      r.update_attribute(:result, 1) if (r.score >= 40)
    end
   add_index :reports, :result
  end
end

But when I type 'bin/rake db:migrate' i get the following error:

rake aborted! StandardError: An error has occurred, this and all later migrations canceled: undefined method `<' for nil:NilClass

Please help, how can I write a conditional 'if' in a rails migration?

1

1 Answers

0
votes

score field is nil for one of report's row. Ruby can't compare nil.

Let's if score is nil then result will be 0

class AddResultToReports < ActiveRecord::Migration
  def change
    add_column :reports, :result, :integer
    add_index :reports, :result

    Report.find_each do |r|
      if r.score.nil? || r.score < 40
        r.update_attribute(:result, 0) 
      else
        r.update_attribute(:result, 1)
      end
    end
  end
end