Skip to content

Default value not populating in migration with Rails and Postgresql

I am currently trying to run this migration:

class AddDroppedProjectsCountToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :dropped_projects, :integer, {:default=>0, :required=>true}

  def self.down
    remove_column :users, :dropped_projects

The column is added correctly, but none of the old records are populated with 0. They are nil. I have tried using default=>'0' as well, to no avail. Any idea why this might be happening? (Rails 3.0.3)

Edited to add: When I create a new user it works fine, and everything looks correct. It’s just the old users that still have nil for that value in the table.


What happens if you say:

def self.up
  add_column :users, :dropped_projects, :integer, :null => false, :default => 0

instead? Without the :null=>false you’re still allowing NULL in dropped_projects so there’s no reason for PostgreSQL to make them 0. Also, I don’t think :required is a valid option for add_column; since the options are just a simple Hash and add_column only looks for options it knows about, your stray :required option is silently ignored.