Rails Migration changing column to use Postgres arrays

后端 未结 5 1641
故里飘歌
故里飘歌 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:57

    Using Rails 4.2 on postgresql 9.4 I was looking to do this and preserve my pre-existing string data as the first element in one element arrays.

    It turns out that postgresql cannot coerce a string into a text array without a USING expression to tell it how.

    After much fiddling with delicate postgres syntax, I found a good middle way with active record:

    def change
      change_column :users, :event_location, :text, array: true, default: [], using: "(string_to_array(event_location, ','))"
    end
    

    The only direct postgresql there is the (string_to_array() ) function call. Here are the docs on that--note that you have to supply a delimiter.

提交回复
热议问题