How can I store a hash in my database? How can I store a hash in my database? ruby ruby

How can I store a hash in my database?


Rails 4 adds support for the Postgres hstore data type which will let you add hashes directly into your (postgres) database.

If you are using Rails 4 and Postgres, you can use hstore in your migration:

def up  execute "create extension hstore"  add_column :table, :column, :hstoreenddef down  remove_column :table, :columnend

That execute command will enable hstore in Postgres, so you only have to do that once.

This will enable you to store a hash in :column just like you would any other data type.


There are two ways to do this:

  1. Serialize your hash and store it in a text field.
  2. Split the hash and store each key in a separate row.

The problem with the first approach is that finding and manipulating is difficult and expensive. For example, prefix a "0" before the telephone number of all employees working in Foo Inc. will be a nightmare, compared to storing the data in regular tabular format.

Your schema would be:

employees (id, created_at, updated_at)employee_details (id, employee_id, key, value)

So, to store

"company" => "Foo Inc","telephone" => "555-5555"

you would do:

employees: 1, 2012-01-01, 2012-01-01employee_details (1, 1, "company", "Foo Inc"), (2, 1, "telephone", "555-5555")

Drawbacks of this approach: Rails does not natively support such kind of a schema.


You can use serialization with 3 options: Marshal in binary format, YAML and JSON human-readable formats of data store.

Once you are trying each of methods, do not forget to measure time to serialize and deserialize as well. If you need to pull data back in origin format, JSON is the good choice to use, because you don't need to deserialize it, but use it as a string itself.