Ruby on Rails: How do I add a not null constraint to an existing column using a migration?

Ruby on-RailsDatabaseMigrationConstraintsNotnull

Ruby on-Rails Problem Overview


In my Rails (3.2) app, I have a bunch of tables in my database but I forgot to add a few not null constraints. How can I write a migration which adds not null to an existing column?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can also use change_column_null:

change_column_null :table_name, :column_name, false

Solution 2 - Ruby on-Rails

For Rails 4+, nates' answer (using change_column_null) is better.

Pre-Rails 4, try change_column.

Solution 3 - Ruby on-Rails

  1. Add column with default value

  2. Remove default value

add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil

Solution 4 - Ruby on-Rails

If you are using it on a new create migration script/schema here is how we can define it

class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
    t.string :name, null: false     # Notice here, NOT NULL definition
    t.string :email, null: false
    t.string :password, null: false
    t.integer :created_by
    t.integer :updated_by 

    t.datetime :created_at
    t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' }
   end
  end
end

Solution 5 - Ruby on-Rails

In my approach, I add NOT NULL constraint to columns i need in my existing migrated migration. After that, I reset all my migrations by using this command:

> rake db:migrate:reset

This will drop the database, create it again and run all the migrations. You can check your changes in schema.rb.

If you have few columns in simple migrations, you can use this approach.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid RobertsonView Question on Stackoverflow
Solution 1 - Ruby on-RailsnatesView Answer on Stackoverflow
Solution 2 - Ruby on-RailsDan WichView Answer on Stackoverflow
Solution 3 - Ruby on-RailsrndrferoView Answer on Stackoverflow
Solution 4 - Ruby on-RailsManjunath ReddyView Answer on Stackoverflow
Solution 5 - Ruby on-RailsThien NganView Answer on Stackoverflow