怎么做:默认=>0 和 :null =>迁移中的整数字段的假不同? [英] How do :default => 0 and :null => false differ for integer fields in migrations?

查看:14
本文介绍了怎么做:默认=>0 和 :null =>迁移中的整数字段的假不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用迁移来更新数据库,并添加这样的整数字段:

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.

是否需要默认 => 0,如果我有 :null => false?

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 做了两件事:

  1. 告诉您的数据库在查询中指定 NULL 或未指定任何内容时使用0"作为默认值.
  2. 告诉 rails 在创建新对象时使用0"作为默认值.
  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.

第 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.

这篇关于怎么做:默认=>0 和 :null =>迁移中的整数字段的假不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆