Storing Arrays with Active Record

Alec Scully
2 min readFeb 16, 2021

When first learning Active Record, I was under the impression that there was a very limited amount of declarations I could use when creating a table. But when it came time to start my Flatiron phase 4 project, I wanted to have my database store an array of values to be accessed later. Up until that point I was under the assumption that you could only store strings, integers, booleans, etc. I thought that my project idea was going to either flush down the drain, or be an awfully long slog of finding work arounds to store an array.

Example of migration declarations from Active Record Documentation

Luckily after a bit of research I found that there are a few ways that you could store arrays in a database, without having to create janky code.

I created a small example for this where a user could store a list of favorites with a name and list attribute. The only additional thing I added was that I set the list attribute to be an array. This small change takes the list attribute and changes it from expecting just a string to expecting an array containing strings. This can also be done with other types (t.integer for an array of numbers for example).

From there I was able to seed data, creating lists for my favorite fruits, shows, and brothers. When I started a rails console, I checked to see if the array was successfully seeded.

Success!

With that working, we are now able to store and access arrays in our Rails databases for future use.

--

--