Rails Migration changing column to use Postgres arrays

后端 未结 5 1647
故里飘歌
故里飘歌 2020-12-14 03:28

I am trying to change a column in my database so that it can use the Postgres array data type. Currently the table column is of type string.

I am using the following

5条回答
  •  星月不相逢
    2020-12-14 03:39

    Using Rails 4.2 on postgresql 9.4 with a down and a up, base on lrrthomas response. Note: your starting column should have a default of nil

    class ChangeEmailAndNumberColumnForContact < ActiveRecord::Migration
      def up
        change_column :contacts, :mobile_number, :text, array: true, default: [], using: "(string_to_array(mobile_number, ','))"
        change_column :contacts, :email, :text, array: true, default: [], using: "(string_to_array(email, ','))"
      end
    
      def down
        change_column :contacts, :mobile_number, :text, array: false, default: nil, using: "(array_to_string(mobile_number, ','))"
        change_column :contacts, :email, :text, array: false, default: nil, using: "(array_to_string(email, ','))"
      end
    end
    

提交回复
热议问题