【问题标题】:ActiveRecord Migrations - set value of new column based on value of existing columnActiveRecord 迁移 - 根据现有列的值设置新列的值
【发布时间】:2017-06-26 23:04:29
【问题描述】:

我正在运行 Rails 迁移,对于所有记录,我想根据现有列的值 - 'score' 设置新列 'result' 的值。

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

但是当我输入“bin/rake db:migrate”时,我收到以下错误:

rake 中止! StandardError:发生错误,此迁移和所有后续迁移已取消: 未定义的方法 `

请帮忙,如何在 Rails 迁移中编写条件“if”?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    score 字段是nil 用于报告的行之一。 Ruby 无法比较 nil。

    如果scorenil 那么result 将是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
    

    【讨论】:

    • 是的,如果 score 为 nil,它会尝试比较 'nil
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多