Forbes magazine logo Ranked Best Coding Bootcamps 2023

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

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #90

Enroll for June 3rd, 2024