How to solve “Cannot add a NOT NULL column with default value NULL” in SQLite3?

前端 未结 4 1733
时光说笑
时光说笑 2020-11-28 06:43

I am getting the following error while trying to add a NOT NULL column to an existing table. Why is it happening ?. I tried rake db:reset thinking that the existing records

4条回答
  •  北海茫月
    2020-11-28 07:33

    If you have a table with existing rows then you will need to update the existing rows before adding your null constraint. The Guide on migrations recommends using a local model, like so:

    Rails 4 and up:

    class AddDivisionIdToProfile < ActiveRecord::Migration
      class Profile < ActiveRecord::Base
      end
    
      def change
        add_column :profiles, :division_id, :integer
    
        Profile.reset_column_information
        reversible do |dir|
          dir.up { Profile.update_all division_id: Division.first.id }
        end
    
        change_column :profiles, :division_id, :integer, :null => false
      end
    
    end
    

    Rails 3

    class AddDivisionIdToProfile < ActiveRecord::Migration
      class Profile < ActiveRecord::Base
      end
    
      def change
        add_column :profiles, :division_id, :integer
    
        Profile.reset_column_information
        Profile.all.each do |profile|
          profile.update_attributes!(:division_id => Division.first.id)
        end
    
        change_column :profiles, :division_id, :integer, :null => false
      end
    
    end
    

提交回复
热议问题