简体   繁体   中英

rails+postgres migration empty string vs nil

I ran a this 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

Then I tried to run this one but didn't work:

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

I was surprised and didn't understand how it was possible. Then I hit up the console and realized that the value of the fields were not "" but nil . I checked then a few other tables and saw that some tables and fields have "" as default and some have nil .

I'd like to have the empty strings in all the tables. So my questions:

  1. When I generate a new migration how can I make sure my string type columns will have "" as default. So for instance what should I have done differently in the code I provided?

  2. What's the convention to change the nil values to "" for existing tables?

  1. When I generate a new migration how can I make sure my string type columns will have "" as default. So for instance what should I have done differently in the code I provided?

Documentation has you covered :

add_column :product_customers, :name, :string, default: ""

If you want to disallow NULL value in your DB columns, then also add null: false to your migration:

add_column :product_customers, :name, :string, default: "", null: false

  1. What's the convention to change the nil values to "" for existing tables?

To change column's default value use change_column_default . if you want to change the DB rule for allowing NULL values, use change_column_null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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