Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres migrate uuid column type with default value doesn't work

My migration is

class AddUuidToUsers < ActiveRecord::Migration
  def change
    add_column :users, :uuid, :uuid, null: false, default: 'uuid_generate_v4()'
    add_index :users, :uuid
  end
end

The schema is changed with:

t.uuid     "uuid",                               default: "uuid_generate_v4()"

As you see, we the null: false is not added, not sure why?

But when I try with a common column type for instance string it works well.

Is there any limitation for :uuid column type that we can't use null: false?

like image 308
Hieu Pham Avatar asked Sep 21 '26 08:09

Hieu Pham


1 Answers

Rails 4.2 totally ignore null option for uuid columns with a default value. You may check a column object for your model:

> User.columns[2] # number of uuid column
=> #<ActiveRecord::ConnectionAdapters::PostgreSQLColumn:0x007fe6fee53f20 ...
@sql_type="uuid", @null=true, @default=nil, @default_function="uuid_generate_v4()">

But migration options was the same as in your example:

add_column :users, :uuid, :uuid, null: false, default: 'uuid_generate_v4()'

Rails 5.0 had fixed this bug. Column object keeps null option for the same migration:

> User.columns[2]
=> #<ActiveRecord::ConnectionAdapters::PostgreSQLColumn:0x007fa6c3722650 ...
@sql_type="uuid", @type=:uuid, @null=false, @default=nil, @default_function="uuid_generate_v4()", @collation=nil, @comment=nil>

And schema.rb also contains null: false:

t.uuid   "uuid", default: -> { "uuid_generate_v4()" }, null: false
like image 151
Ilya Lavrov Avatar answered Sep 24 '26 01:09

Ilya Lavrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!