Migration to create default value

非 Y 不嫁゛ 提交于 2020-01-14 05:50:09

问题


So I want to know whether we can write a new migration just to set default value of a field,which is already created. I know how to write edit the old migration and set its default value. I want to do this because I have done so many migrations and I cant roll back now and edit that file. And also, Is there any way to rollback to a particular migration?

Thanks in advance


回答1:


Run

rails g migration add_default_value_to_table

then in the migration file

def up
    change_column :table_name, :column_name, :string, :default => "abcd"
end

def down
    change_column :table_name, :column_name, :string, :default => nil
end

I've used datatype string as an example, you can do it for column with any datatype




回答2:


To rollback a particular migration:-

rake db:migrate:down VERSION=20080906120000

Then edit the migration and add the default value to that field and run the migration again as

rake db:migrate:up VERSION=20080906120000


来源:https://stackoverflow.com/questions/23563978/migration-to-create-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!