Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONB not working with Rails 5? JSON field returns as a string

I have a jsonb field and for whatever reason, when I call the field, it comes back as a string. Here's the migration:

class CreateConferences < ActiveRecord::Migration[5.0]
  def change
    create_table :conferences do |t|
      t.references :user
      t.string :name
      t.jsonb :payload, default: '{}'
      t.jsonb :processed_payload

      t.timestamps
    end
  end
end

If I create a new conference ( Conference.create(user: user, name: 'test', payload: '{}') ) and then fetch the payload it comes back as a String. What am I missing here??

Apparently this is now the "expected behavior" in rails now as per this issue. Not sure how to make this work now...

Guess I need to call JSON.parse() after every request?

like image 699
Nick ONeill Avatar asked Aug 12 '16 22:08

Nick ONeill


1 Answers

My current solution is to use the following getter method:

def payload
    (self[:payload].class == String) ? JSON.parse(self[:payload]) : self[:payload]
end

This seems odd that it would be the behavior required to make it work but if you want the prior Rails 4 functionality, you'll need to switch over to this based on the comments here.

Update

I randomly ended up on my question while looking into a completely different issue but figured I'd update this answer.

The answer was to not have the default value be '{}' but instead be {}. Pretty simple fix :)

like image 150
Nick ONeill Avatar answered Sep 18 '22 18:09

Nick ONeill