SwitchUp SwitchUp Ranked Best Coding Bootcamps 2025

Store arrays or hashes in Rails ActiveRecord

Altcademy Team wrote on 7 February 2018

If you have an attribute that needs to be saved to the database as an object (hash, json or array), and retrieved as the same object, then specify the name of that attribute using ActiveRecord::Base's serialize method and it will be handled automatically.
Assuming you are using Postgres.

Step 1: Define such attribute (ie. metadata) as string type in your migration file of the model (ie. Model). Postgres will store an object as a string.
class CreateUsers < ActiveRecord::Migration def change # we create the User table as an example create_table :users do |t| # we create an attribute called "metadata" as an example t.string :metadata t.timestamps null: false end end end

Step 2: In your User model, serialize the attribute of your choice, in the case, metadata.
class User < ActiveRecord::Base serialize :metadata, JSON # Alternatively, you can also serialize an attribute as a Hash or Array # serialize :metadata, Hash # serialize :metadata, Array end

References:

Trusted by

Students and instructors from world-class organizations

Join the upcoming Cohort #111

Enroll for March 2nd, 2026