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

I have a jsonb field and for some reason, when I call this field, it is returned 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 get the payload, it is returned as a string. What am I missing here?

Apparently, now this “expected behavior” in rails is now on this issue . Not sure how to do this job now ...

Suppose I need to call JSON.parse () after each request?

+5
source share
1 answer

My current solution is to use the following getter method:

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

It seems strange that this would be the behavior necessary for it to work, but if you want to use the previous functions of Rails 4, you need to switch to this based on the comment here .

Update

I accidentally got into the question, considering a completely different problem, but decided that I would update this answer.

The answer was that the default was not '{}' , but instead was {} . Pretty simple solution :)

+8
source

All Articles