rails + postgres migration空字符串vs nil

时间:2016-05-26 17:54:59

标签: ruby-on-rails postgresql migration

我进行了这次迁移:

def up
  add_column :product_customers, :name, :string
  add_column :product_customers, :email, :string
end

def down
  remove_column :product_customers, :name, :string
  remove_column :product_customers, :email, :string
end

然后我尝试运行这个但是没有用:

def up
  change_column_null :product_customers, :name, false
  change_column_null :product_customers, :email, false
end

def down
  change_column_null :product_customers, :name, true
  change_column_null :product_customers, :email, true
end

我很惊讶,也不明白它是如何可能的。然后我打开控制台并意识到字段的值不是""而是nil。我检查了一些其他表格,发现有些表格和字段默认为"",有些表格为nil

我想在所有表中都有空字符串。所以我的问题:

  1. 当我生成新的迁移时,如何确保我的字符串类型列默认为""。那么,例如我在我提供的代码中应该做些什么呢?

  2. 将现有表格的nil值更改为""的惯例是什么?

1 个答案:

答案 0 :(得分:1)

  
      
  1. 当我生成新的迁移时,如何确保我的字符串类型列将具有""作为默认值。那么,例如我在我提供的代码中应该做些什么呢?
  2.   

Documentation有你covered

ArrayAdapter

如果您想在数据库列中禁用add_column :product_customers, :name, :string, default: "" 值,请在迁移中添加NULL

null: false
  
      
  1. 将nil值更改为""的惯例是什么?对于现有表格?
  2.   

要更改列的默认值,请使用add_column :product_customers, :name, :string, default: "", null: false 。如果您要更改允许change_column_default值的数据库规则,请使用NULL