The beautiful world of hstore (PostgreSQL)

In my recent project I stumbled across the need to store, let’s say an array of elements (in my app a user can add to this to-be-purchased item additional services. Therefore I need to somewhere store those additional services). One idea might be to create an additional model and connect cart_items with additional services through some „additionalservization“ join table.

However this is the man’s rails world and things are meant to be easy. And here comes the hstore – awesome extension for your PostgreSQL which allows you to store hash values.

Let’s start simple

Log in into your postgreSQL:

\connect app_database_development

this leads to:
=> psql (9.4.1, server 9.4.2)
You are now connected to database "app_development" as user "user".

app_development-# CREATE extension hstore;

That’s it, now your database supports this extension.

Now it’s time to generate the migration:

rails g migration AddDataToLineItems addservices:hstore
rake db:migrate

Now jump right into rails console:

2.2.0 :004 > @li = LineItem.last
2.2.0 :005 > @li.addservices = {first: 4, second: 'one', third: 'some more text'}
 => {:first=>4, :second=>"one", :third=>"some more text"}

Wasn’t that easy and awesome?

Veröffentlicht von


Hello! My name is Anton. I am a passionate project manager who loves digging deep into code. You can check my Github and CodeEval. Hopefully my thoughts on management can lead you to one or another good idea.