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 the record has default value 0 but for other values like 1, 2 it should remain the same. how can i do it?
To change a default value, use ALTER col_name SET DEFAULT : ALTER TABLE mytbl ALTER j SET DEFAULT 1000; Default values must be constants. For example, you cannot set the default for a date-valued column to NOW( ) , although that would be very useful.
Default values, in the context of databases, are preset values defined for a column type. Default values are used when many records hold similar data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With