How do I migrate an ActiveRecord model attribute from json to jsonb?

↘锁芯ラ 提交于 2019-12-10 17:48:34

问题


What should the migration look like? I would like to take advantage of the jsonb array querying technique.


回答1:


I would write the migration this way:

def change
  reversible do |dir|
    dir.up { change_column :models, :attribute, 'jsonb USING CAST(attribute AS jsonb)' }
    dir.down { change_column :models, :attribute, 'json USING CAST(attribute AS json)' }
  end
end

I don't know how this compares performance-wise to other solutions, but I tested this on a table with 120,000 records, each record having four json columns and it took me about a minute to migrate that table. Of course, I guess it depends on how complex the json structure is.

Also, notice that if your existing records have a default value of {}, you have to add to the above statements default: {}, because otherwise you'll have jsonb columns, but the default value will remain as '{}'::json.



来源:https://stackoverflow.com/questions/50024841/how-do-i-migrate-an-activerecord-model-attribute-from-json-to-jsonb

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