How to change a nullable column to not nullable in a Rails migration?
I created a date column in a previous migration and set it to be nullable. Now I want to change it to be not nullable. How do I go about doing this assuming there are null rows in that database? I'm ok with setting those columns to Time.now if they're currently null.
如果你在迁移中这样做,那么你可以这样做:
# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)
# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false
In Rails 4, this is a better solution (DRY):
change_column_null :my_models, :date_column, false
To ensure no records exist with null
values in that column:
MyModel.update_all({ date_column: Time.now }, { date_column: nil })
Rails 4 (other Rails 4 answers have problems):
def change
change_column_null(:users, :admin, false, <put a default value here> )
# change_column(:users, :admin, :string, :default => "")
end
Changing a column with NULL values in it to not allow NULL will cause problems. This is exactly the type of code that will work fine in your development setup and then crash when you try to deploy it to your LIVE production. You should first change NULL values to something valid and then disallow NULLs. The 4th value in change_column_null
does exactly that. See documentation for more details.
Also, I generally prefer to set a default value for the field so I won't need to specify the field's value every time I create a new object. I included the commented out code to do that as well.
链接地址: http://www.djcxy.com/p/47184.html上一篇: 通过迁移向列添加默认值