Understanding rails migration statement (:null => false)

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I am trying to understand the following statement, it is from a rails migration file:

x.datetime "new",     :null => false x.datetime "update",  :null => false 

I understand the the first part of both statements (everything before the comma) but I am unsure on the null portion

:null => false 

Is this basically saying "if it does not exist, then it is false?" The logic just seems a bit strange, any clarification on this would be greatly helpful.

回答1:

Edit: I had taken the question to be about syntax and translation since it originally mentioned CoffeeScript. For purpose, refer to Peter Bloom's answer.


I am not sure what the :null => false means exactly.

The => operator is a key/value separator in Ruby, defining a Hash with a :null key set to false. It's similar to : for an Object literal in CoffeeScript/JavaScript -- { null: false }.

When used in an argument list, it's one option for allowing/imitating named arguments in Ruby.

The other main difference is that CoffeeScript/JavaScript use Strings for keys while Ruby typically uses Symbols -- "null" (cs/js) vs. :null (rb).

So, the syntactic equivalent in CoffeeScript would be:

x.datetime "new",     null: false x.datetime "update",  null: false 

In JavaScript, that's:

x.datetime("new",    { null: false }); x.datetime("update", { null: false }); 


回答2:

:null => false in a Rails migration tells your database not to accept NULL values. It can be used with :default => 0 to tell your database to use '0' as the default value (a) when NULL or nothing is specified in a query or (b) when creating or updating an object. (Remember, '0' and NULL are not the same things.)



回答3:

Firstly, rather than use x I'd use the standard t variable that is used in migrations.

Now, inside migration files the t object in create_table is actually of type ActiveRecord::ConnectionAdapters::TableDefinition.

And,

t.datetime "new",    :null => false t.datetime "update", :null => false 

actually translates to

t.column("new", :datetime, { :null => false }) t.column("update", :datetime, { :null => false }) 

where the last argument is the options argument of the column method.

According to the documentation one of these options is :null which allows or disallows NULL values in the column.

So, in summary :null => false would mean "Do not allow NULL values in the new or update column".



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!