I want to add a new field in a rails table, This field is going to be not null. How do I handle entries that are all ready in the database ?
2 Answers
If you create the migration to add the new non-null column, and simply specify a default value, all records that exist will then take on the default value
class AddNotNullColumn < ActiveRecord::Migration
def change
add_column :table_name, :column_name, :column_type, null: false, default: 'default_value'
end
end
This should do it all for you in one go
Comments
Create a rake task and assign default values to null columns. You can do same in migration also.
You must add migration for that because migration run only once. But rake task can be run multiple times. And don't need to worry that you run rake task or not.
Your migration should have :
def migrate(direction)
super
Xyz.where(:price_currency => nil).each do |xyz|
xyz.update(:price_currency => "USD") if direction == :up
end
def change
add_column :xyzs, :price_currency, :sting, default: "USD", null: false
end