问题描述
我需要将字段的默认值从0更改为3,但是要注意的是我已经有成千上万的记录,并且仅当记录的默认值为0时才希望这些记录将值从0更改为3.其他值,例如1、2,则应保持不变.我该怎么做?
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?
推荐答案
在迁移中,您应该使用change_column方法更改表设置,如下所示:
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
然后要更新所有现有记录,而不是遍历所有记录并分别更新它们,可以使用update_all方法,如下所示:
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.
这篇关于迁移以更改字段的默认值,并仅在具有旧默认值的情况下,将所有现有记录的值更改为新的默认值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!