How to avoid AR confusing way of handling default values for attributes w/ :null => false

How can I avoid AR confusing way of handling default values for
attributes w/ :null => false?

This issue came up before, but I could not find an answer that resolves
the issue, which I outline below:

First, I add a test table using migrations:

class AddTestTable < ActiveRecord::Migration
  def self.up
    create_table "users", :force => true do |t|
      t.column "email", :string, :null => false
      t.column "age", :integer, :null => false

  def self.down
    drop_table "users"

$ script/generate model User

$ script/console

Loading development environment.

=> ""

=> 0
I just dont understand why it defaults email to "" and age to 0 and not
to nil. Nowhere did
I set the default email value to "" and the default age value to 0 in
my migration.

Now if I do $rake db:schema:dump here's what the generated schema looks

ActiveRecord::Schema.define(:version => 1) do

  create_table "users", :force => true do |t|
    t.column "email", :string, :default => "", :null => false
    t.column "age", :integer, :default => 0, :null => false


All of a sudden there is a :default=>"" for email and a default 0 for

The new user would validate fine even if I set validates_presence_of
:email, :age in the model file. It even gets worst if one sets a
foreign key to :null => false, as it would default to 0!

Is there a way of overriding this confusing way that AR has to handle
default values???


Edoardo "Dado" Marcora

Thank you soooo much!


Hi Dominique,

you strategy makes a lot of sense, but I tried it w/ the latest rails
and it still overrides my defaults (even when set to nil) and I am
still getting to be "" and to be 0... I
don't remember AR behaving this way in the past. Any help?


Dominique Plante wrote: