Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing nested Hashes in PostgreSQL with Rails 4 (and Hstore)

I have a Rails app that aggregates a lot of data from Google API's. I store the JSON responses in MongoDB currently (so my Rails app has both pg and mongo). However, today, I've came across PostgreSQL Hstore extension, and I've decided to give it a try.

Unfortunately, I've ran into a problem. JSON given by API's is multiple levels deep, so Ruby Hash after JSON.parse contains hashes, which contain new hashes. However, Hstore is string key/value store, and it only goes 1 level deep. So hashes within first hash just become strings.

The really nasty hack I found to do is to eval the hashes that were turned into strings:

eval("{ "foo" => "bar" }")

I do not like this. Any tips on what to do? Should I keep using MongoDB or is there any better way to store multi-level deep hashes in PG?

like image 807
if __name__ is None Avatar asked Sep 17 '13 23:09

if __name__ is None


1 Answers

setting[:quizzes] # => "{:score=>true, :percent=>true, :weight=>true}"
JSON.parse setting[:quizzes].gsub(/:(\w+)/){"\"#{$1}\""}.gsub('=>', ':')
# => {"score"=>true, "percent"=>true, "weight"=>true}
like image 168
Stanislav Kr. Avatar answered Nov 02 '22 23:11

Stanislav Kr.