问题描述
如果我使用迁移来更新数据库,并且添加了一个像这样的整数字段:
If I use a migration to update a database, and I add an integer field like this:
t.integer :foo :default => 0, :null => false
数据库中现有记录和新记录的默认状态是什么?我希望答案是:-两者都将foo读回为0.
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.
如果我有:null => false,默认=> 0是否必要?
Is default => 0 necessary, if I have :null => false?
只是想了解两者之间的区别...
Just trying to understand the difference between the two...
推荐答案
:null => false
告诉您的数据库不接受NULL
值.
:null => false
tells your database not to accept NULL
values.
:default => 0
做两件事:
- 告诉数据库,如果在查询中未指定
NULL
或未指定任何内容时,将使用默认值"0". - 告诉rails在创建新对象时使用默认值"0".
- Tell your database to use '0' as the default value when
NULL
or nothing is specified in a query. - Tell rails to use '0' as a default value when creating a new object.
第2点确保在保存新对象时,您实际上已经拥有一个有效值.
Point 2 makes sure that when you save your new object, you actually have a valid value in place.
要回答您的问题:如果您不想在数据库中使用NULL
值,请设置:null => false
,否则只需使用:default
参数即可.请注意,"0"和NULL
是不同的东西.
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.
不具有NULL
值对于建立索引或需要向第三方提供直接数据库访问权限可能很重要.
Not having NULL
values might be important for indexing purposes or if you need to provide direct database access to a third party.
这篇关于怎么做:default => 0和:null =>迁移中的整数字段是否为false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!