Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 874
n00b Avatar asked Aug 11 '11 06:08

n00b


People also ask

How do I change the default value in mysql?

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.

What do you mean by default value of a field in a record?

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.


1 Answers

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.

like image 121
DanneManne Avatar answered Sep 19 '22 02:09

DanneManne