Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

ruby on rails - How do :default => 0 and :null => false differ for integer fields in migrations?

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.

Is default => 0 necessary, if I have :null => false?

Just trying to understand the difference between the two...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

:null => false tells your database not to accept NULL values.

:default => 0 does two things:

  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.

Point 2 makes sure that when you save your new object, you actually have a valid value in place.

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.

Not having NULL values might be important for indexing purposes or if you need to provide direct database access to a third party.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...