简体   繁体   English

Rails:即使默认值设置为0,枚举字段仍为零

[英]Rails: Enum field taking nil value even though default value set as 0

I have defined following enum fields in my model: 我在模型中定义了以下enum字段:

class ClientRegistration < ApplicationRecord
  enum status: { pending: 0, registered: 1, activated: 2, suspended: 3 }
  enum cloud_type: { onprem: 0, aws: 1, gcp: 2, azure: 3 }
end

The migration file for the same looks like below: 相同的迁移文件如下所示:

class CreateClientRegistrations < ActiveRecord::Migration[5.2]
  def change
    create_table :client_registrations do |t|
      t.string :instance_id
      t.string :private_ip
      t.string :mac_address
      t.integer :cloud_type, default: 0
      t.string :public_ip
      t.string :region
      t.integer :status, default: 0

      t.timestamps
    end
  end
end

Now the strange thing is, my first column status doesn't get it's default value if I don't specify any. 现在奇怪的是,如果我未指定任何第一列状态,则第一列状态将不为默认值。 Also it doesn't take the first value if I specify explicitly as pending . 另外,如果我明确指定为pending ,则不会采用第一个值。 But it works in case of my second column cloud_type , it gets the default as onprem , if I don't specify any. 但是在第二列cloud_type的情况下它可以onprem ,如果我不指定任何默认值,它将默认为onprem Do I need to change the column_name or so? 我是否需要更改column_name左右?

You can try to add "null: false" to the migration. 您可以尝试向迁移添加“ null:false”。

  t.integer :cloud_type, null: false, default: 0

  t.integer :status, null: false, default: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM