Migration to change default value for a field and change all existing record's value to new default value only if it has old default value.

后端 未结 2 594
死守一世寂寞
死守一世寂寞 2021-02-01 15:51

I need to change the default value of a field from 0 to 3, but the catch is i have thousands of records already and want those records to change the value to 3 from 0 only if th

相关标签:
2条回答
  • 2021-02-01 16:42

    In the migration you should use the method change_column to alter the table settings like this:

    change_column :my_models, :attribute_name, :integer, :default => 3
    

    And then to update all existing records, instead of looping through all records and updating them individually you could use the method update_all like this:

    MyModel.update_all({ :attribute_name => 3 }, { :attribute_name => 0 })
    

    The first argument tells the method what value to set and the second tells it the condition for which rows to update.

    0 讨论(0)
  • 2021-02-01 16:44
    ALTER TABLE your_table MODIFY your_column tinyint(1) NOT NULL DEFAULT 3;
    UPDATE your_table SET your_column=3 WHERE your_column=0;
    
    1. assuming your column is tinyint(1), replace your self if not the same
    2. NOT NULL is assuming you always force the column to be NOT NULl
    0 讨论(0)
提交回复
热议问题