What have you found for these years?


Using PostgreSQL JSONB with Rails 4.1

So we just upgraded PostgreSQL to 9.4 and I was so excited to migrate to
JSONB in order to use various querying functions which don't have
equivalents for JSON.

After migration was written, all API tests were passed, then I realized
that this won't work for Rails 4.1 because it didn't recognize JSONB.
(We run API tests first, then Rails tests)

Doh. We can't upgrade Rails because we're locked at an older version of
devise (3.0.4 to be specific), which won't work with Rails 4.2.

Then I finally made my mind to remove devise, rewrite everything, and
upgrade Rails. This was a very hard decision because then I need to figure
out the black magic inside devise, which would be a very painful process.

Fortunately, @wildjcrt sent me a quote from @boriscy:

One note, Rails 4.1 supports json but not jsonb, you need to add

serialize :col, JSON

to make work jsonb in rails 4.1
p.s. I was too lazy to search around because I am so tired of fixing black magic
and I just want to rewrite everything to make things under control.

That's not a full solution but an hint that it's not that broken,
and it could probably be easily patched to work. After some time
playing around, I was able to make JSONB work for Rails 4.1 without
touching all the models we have. Because it would also be painful to
edit all the models using JSONB.

This is the patch to make JSONB work with Rails 4.1.

Basically, register the OID for jsonb and after all the models were
loaded, walk through all the columns which data type is jsonb and
default to '{}::jsonb' (because we only use it this way and the others
could come from que which I shouldn't be patching with)

Sequel was used here because we have it and it works great. If you
want to work with ActiveRecord to fight with this, go ahead, I think
it should also work.

After this patch was applied, all tests passed.

Here's the other thread on twitter.

0 retries:

Post a Comment

Note: Only a member of this blog may post a comment.

All texts are licensed under CC Attribution 3.0