56

If I use a migration to update a database, and I add an integer field like this:

t.integer :foo :default => 0, :null => false

What is the default state of existing and new records in the database? I hoping the answer is: - Both will read back foo as 0.

Is default => 0 necessary, if I have :null => false?

Just trying to understand the difference between the two...

cmaughan
  • 2,596
  • 5
  • 30
  • 35

1 Answers1

112

:null => false tells your database not to accept NULL values.

:default => 0 does two things:

  1. Tell your database to use '0' as the default value when NULL or nothing is specified in a query.
  2. Tell rails to use '0' as a default value when creating a new object.

Point 2 makes sure that when you save your new object, you actually have a valid value in place.

To answer your question: If you don't want NULL values in your database, set :null => false, otherwise just use the :default parameter. Mind you, '0' and NULL are not the same things.

Not having NULL values might be important for indexing purposes or if you need to provide direct database access to a third party.

Ariejan
  • 10,910
  • 6
  • 43
  • 40
  • By this, do you mean that it will read back as 0 if I have an existing database record before the migration? So if I do Table.value, on an old record, value will == 0? – cmaughan Oct 26 '10 at 17:15
  • Yes. If you have a table column that contains `NULL` values, but you set a default, then that default will be returned. – Ariejan Oct 26 '10 at 17:40
  • 1
    This is the enlightening, valuable info: "Not having NULL values might be important for indexing purposes or if you need to provide direct database access to a third party." – ahnbizcad Jul 28 '14 at 12:40
  • great answer, even if it's a simple question. – ahnbizcad Jul 29 '14 at 00:00
  • 2
    @ahnbizcad don't understand this, how is direct connection for a 3rd party related to not wanting null values? – Joel Blum May 08 '19 at 08:48