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

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

问题描述

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

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

  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.

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

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