Converting existing string field type to array field type in database | Rails + PostgreSQL

Viewed 239

I'm using Ruby on Rails with Postgresql and had a String db field for attachment. Now I support multi file upload and need to convert my Attachment String db field to String Array so that I can host multiple files.

How do I convert the existing "String" db field to "String Array" using Rails Console?

enter image description here

enter image description here

1 Answers

You don't convert the "String" db field into a "String Array". What you're looking for is a serializer. Do the following in your model

class Post < ApplicationRecord
  serialize :attachment, Array
end

# Try in rails console
Post.find 117
#=> #<Post id: 117, attachment: ["11.jpg", "22.jpg", "33.jpg"] ...>

You can save provide an array while saving it, and it will convert it to string and store it & while extracting it will convert the string to an array and return you the array

Also you might want to rename your column from attachment to attachments since its will contain an array.

Related