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
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.
ALTER TABLE your_table MODIFY your_column tinyint(1) NOT NULL DEFAULT 3;
UPDATE your_table SET your_column=3 WHERE your_column=0;
tinyint(1)
, replace your self if not the sameNOT NULL
is assuming you always force the column to be NOT NULl