2017-02-09 12 views
0

すべてのレコードに対して、既存の列の値に基づいて新しい列 'result'の値を設定する、 'スコア'。ActiveRecord Migrations - 既存の列の値に基づいて新しい列の値を設定します。

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 

しかし、私は入力したときに:私は次のエラーを取得する「ビン/すくいデシベルを移行」:

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

レールの移行で「場合は、」私は、条件を書くことができるか、助けてください?

答えて

0

scoreフィールドは、レポートの行の1つにはnilです。 Rubyはnilを比較できません。

レッツ・scorenilであればスコアがnilであるならば、result0

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 
+0

うん、まあ、それはゼロ<40 '場合を比較しようとしていたことになり、それが失敗した理由です。私の悪い。ありがとう! – GregF

関連する問題