Principal Backend Software Engineer at StackShare·
Shared insights
on
PostgreSQLPostgreSQLRailsRailsRubyRuby

Sometimes I need a quick way to store a list of things, without new PostgreSQL tables and Rails associations. I just want to add a field to an existing table and call it a day. This is useful for simple features, or when the future is uncertain.

For example, you could store T-shirt sizes in a 'S,M,L,XL' string, but then you'd have to join/split when storing/reading. What if I told you that you could delegate all this dirty work to Postgres?

You can store a ['S','M','L','XL'] array with the Postgres array type:

add_column :products, :sizes, :string, array: true, default: []

When reading the value from the DB, Rails will present it to you as a Ruby array. Nice!

And if you want to store hashes like [{ 'size': 'S', 'color': 'Red' }, { 'size': 'M', 'color': 'Green' }], Postgres' jsonb type has you covered too:

add_column :products, :sizes, :jsonb, default: []

Happy #Hacking!

#DataTypes

READ LESS
6 upvotes·9.1K views
Avatar of Jerome Dalbert

Jerome Dalbert

Principal Backend Software Engineer at StackShare