2

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 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

WOW! That actually worked! I wasted over 1 week with many hours for it with no result! Thank you mate! I'm going to read and learn more about this serialize!
Yes, you can even have json, hash etc. You can even create your custom structures by having load and dump as class methods in your serializer. Good luck

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.