In our database we currently have a table with a String country column. This stores a single country code (e.g. US). The country column has an index. We now need to store multiple country codes in the column, so we want to convert it to a PostgreSQL String array. My current migration code is
def change
reversible do |direction|
change_table :product do |table|
direction.up do
table.remove_index(:country)
table.rename :country, :countries
table.change :countries, :string, array: true
table.index :countries
end
direction.down do
table.remove_index(:countries)
table.change :countries, :string, array: false
table.rename :countries, :country
table.index :country
end
end
end
end
however when I run the migration I get the error
PG::DatatypeMismatch: ERROR: column "countries" cannot be cast automatically to type character varying[]
HINT: You might need to specify "USING countries::character varying[]"
and I am not sure how to specify how I want the conversion to be performed.
I would like to know how to change my migration so that
- The
countriescolumn is an array - The
countriescolumn is indexed - The existing string value of the
countrycolumn is saved into the array
or in other words, so that
country: 'US'
becomes
countries: ['US']