1

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 ?

1
  • can you explain more.? what you want to do.? Commented Aug 21, 2015 at 11:39

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.