Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding rails migration statement (:null => false)

I am trying to understand the following statement, it is from a rails migration file:

x.datetime "new",     :null => false
x.datetime "update",  :null => false

I understand the the first part of both statements (everything before the comma) but I am unsure on the null portion

:null => false

Is this basically saying "if it does not exist, then it is false?" The logic just seems a bit strange, any clarification on this would be greatly helpful.

like image 516
FluxEngine Avatar asked Mar 12 '13 17:03

FluxEngine


2 Answers

:null => false in a Rails migration tells your database not to accept NULL values. It can be used with :default => 0 to tell your database to use '0' as the default value (a) when NULL or nothing is specified in a query or (b) when creating or updating an object. (Remember, '0' and NULL are not the same things.)

like image 157
Peter Bloom Avatar answered Oct 13 '22 21:10

Peter Bloom


Firstly, rather than use x I'd use the standard t variable that is used in migrations.

Now, inside migration files the t object in create_table is actually of type ActiveRecord::ConnectionAdapters::TableDefinition.

And,

t.datetime "new",    :null => false
t.datetime "update", :null => false

actually translates to

t.column("new", :datetime, { :null => false })
t.column("update", :datetime, { :null => false })

where the last argument is the options argument of the column method.

According to the documentation one of these options is :null which allows or disallows NULL values in the column.

So, in summary :null => false would mean "Do not allow NULL values in the new or update column".

like image 38
Dwayne Crooks Avatar answered Oct 13 '22 20:10

Dwayne Crooks