how to use jsonb in rails

做~自己de王妃 提交于 2019-12-30 07:26:06

问题


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

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

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


回答1:


For migrating this, you can do the following. 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 find out how to query jsonb in Rails 4.2, checkout this article




回答2:


Here is it how it worked with Rails 4.2

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

The answer above threw errors for me.



来源:https://stackoverflow.com/questions/27343231/how-to-use-jsonb-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!