开发者

What is the difference between default and null in migration

开发者 https://www.devze.com 2023-03-19 06:21 出处:网络
What is the difference between: t.boolean :test, :default => true and t.boolean :test, :null => true

What is the difference between:

t.boolean :test, :default => true

and

t.boolean :test, :null => true

and

t.boolean :test, 开发者_如何学编程:default => true, :null => true

EDIT

Does the following make any sense?

t.boolean :test, :default => true, :null => false


"null" means "are you allowed to enter a null value in this column"?

Whereas "default" means "if there is a null value in this column ... then use this default value instead"

So, for your examples:

t.boolean :test, :default => true

"this boolean column will insert a true if you don't bother setting a value for it"

t.boolean :test, :null => true

"this boolean column will let you set it to true, false or null - and it will stay the way you set it"

t.boolean :test, :default => true, :null => true

"this boolean column will let you set it to true, false or null... but if you set it to null it will automatically be set to true"


:default - The column’s default value. Use nil for NULL.

:null - Allows or disallows NULL values in the column. This option could have been named :null_allowed.

In the first option, if you don't specify anything, rails will put true In the second option, it will allow the value to be null. In the third option, both apply, the values can be true, false and nil


To answer OP's question:

Does the following make any sense?

t.boolean :test, :default => true, :null => false

Sure, let's take a look at the possible SQL events. (Bear in mind the default parameter you set takes effect on INSERT INTO statements like the following.)

INSERT INTO table_name id, test VALUES 1, NULL; # This should raise an error
INSERT INTO table_name id VALUES 1;             # This will default test column's value to true

So, it may make sense - if you want to explicitly disallow NULL values (should an attempt to made to set the value to NULL directly), and you also want to coerce missing or absent values on the test column to true during INSERT INTO statements.

0

精彩评论

暂无评论...
验证码 换一张
取 消