Ruby-on-rails 迁移中的整数字段的 :default => 0 和 :null => false 有何不同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4012871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do :default => 0 and :null => false differ for integer fields in migrations?
提问by cmaughan
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.
数据库中现有记录和新记录的默认状态是什么?我希望答案是: - 两者都会将 foo 读回 0。
Is default => 0 necessary, if I have :null => false?
如果我有:null => false,是否需要默认 => 0?
Just trying to understand the difference between the two...
只是想了解两者之间的区别......
回答by Ariejan
:null => falsetells your database not to accept NULLvalues.
:null => false告诉您的数据库不要接受NULL值。
:default => 0does two things:
:default => 0做两件事:
- Tell your database to use '0' as the default value when
NULLor nothing is specified in a query. - Tell rails to use '0' as a default value when creating a new object.
- 当
NULL查询中未指定或未指定任何内容时,告诉您的数据库使用“0”作为默认值。 - 告诉 rails 在创建新对象时使用“0”作为默认值。
Point 2 makes sure that when you save your new object, you actually have a valid value in place.
第 2 点确保当您保存新对象时,您实际上拥有一个有效的值。
To answer your question: If you don't want NULLvalues in your database, set :null => false, otherwise just use the :defaultparameter. Mind you, '0' and NULLare not the same things.
回答您的问题:如果您不想NULL在数据库中:null => false使用值,请设置,否则只需使用:default参数。请注意,“0”和“0”NULL不是一回事。
Not having NULLvalues might be important for indexing purposes or if you need to provide direct database access to a third party.
没有NULL值对于索引目的或如果您需要向第三方提供直接数据库访问可能很重要。

