Search code examples
arraysrubydatabasepostgresqlsequel

How to save array in database correctly?


I want to add array in database. I use ruby, sequel and postgresql, but question about true way, and not program realization. I see 3 path:

  1. Use special adapters. It help to save array like [1,2,3,4] in db after some changes: in database it will look like "{1,2,3,4}". BUT after it I don't know how to convert this entry back to [1,2,3,4] without bullshits.
  2. Convert array to json and save it to database. Array like [1,2,3,4] will be look like "[1,2,3,4]". And I can easy convert back by JSON.parse.
  3. Convert array by Marshal and save. Array [1,2,3,4] will be look like "\x04\b[\ti\x06i\ai\bi\t", but it riskily, because data can be changed after ruby update (or I am wrong) Can anybody to tell about true way?

Solution

  • Sequel supports Postgres Array columns natively, assuming you don’t need to normalize yourschema further.

    How do I define an ARRAY column in a Sequel Postgresql migration?

    http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_array_rb.html