Dec 13, 2017
Tiny jsonb gotcha in Rails
If you’re using Postgres 9.4+ in your Rails application, you get to create columns in the jsonb type, which lets you store non-relational data.
To do this, you add the column in a migration as usual, like so:
add_column :users, :preferences, :jsonb, default: '{}' Now, you can update the preferences column by doing something like
user = User.find(1)
user.update(preferences: {screen_timeout: 30, quality: 'high'}) And access the preferences by doing:
timeout = user.preferences['screen_timeout'] # important to note that all keys become strings
Makes sense right?
There’s a teeny problem with the above example. If you create the migration like I did, by setting the default to a String and you try to retrieve it as a Hash, it won’t work.
To make sure your default value is returned as a Hash and not a String, do your migrations like this:
add_column :users, :preferences, :jsonb, default: {} Just remove the quotation marks and you’re good to go!
P.S: I discovered this today and it struck me just how many tutorials create the migration(s) with the quotes left in when the desired behaviour would be to get the stored JSON as a hash. That’s why I decided to write this.