How to use jsonb in rails

I have a rails project with Postgresql 9.4 as a backend. I have a column:

t.json :slot_details, null: false, default: {}

How do I change this to JSONB from JSON? Should I add an index and what will be changed to JSONB?

+1
source share
2 answers

This is how it worked with Rails 4.2

t.jsonb :slot_details, index: true, default: {}

The answer above threw me errors.

+3
source

To perform the migration, you can do the following. The payload in this case was originally a json field.

  class AlterJsonbToJsonAndBack < ActiveRecord::Migration                      
    def up                                                                     
      change_column :dynamics, :payload, 'jsonb USING CAST(payload AS jsonb)'  
    end                                                                        

    def down                                                                   
      change_column :dynamics, :payload, 'json USING CAST(payload AS json)'    
    end                                                                        
  end                                                                          

To learn how to request jsonb in Rails 4.2, check out this article.

+6
source

Source: https://habr.com/ru/post/1530604/


All Articles