7

I have a table has a string column contains json data each record is like

{"id":1,"type":"car","name":"bmw"}
{"id":2,"type":"car","name":"Fiat"}
{"id":3,"type":"truck","name":"RAM"}

now I need to make a migration to remove name's element from json string by rails ActiveRecord::Migration[5.0] to becomes like this

{"id":1,"type":"car"}
{"id":2,"type":"car"}
{"id":3,"type":"truck"}
4
  • maybe this similar question has what you need Commented Jul 26, 2017 at 15:52
  • not actually. Seems no body uses migrator to update records . somebody told me make a script and run it by rake . I don't know if it's best practice of doing that or not Commented Jul 26, 2017 at 16:02
  • I've done the same via a rake script. If you have a lot of records (50K +) it will take a long time and tie up one postgres connection and some memory, but the impact really is minor I believe. Use find_each to reduce the memory impact. And make sure you have an extra postgres connection to spare, otherwise you'll have server workers or background threads with no access to the DB when they need it. Commented Jul 26, 2017 at 16:11
  • yes exactly , thanks Commented Jul 26, 2017 at 16:31

2 Answers 2

7

If the database is Postgresql and the column is jsonb, then assuming you want to operate in the car table column

<MODEL_NAME>.update_all("car = car - 'name'")

It can be done via Rake task or a data migration

Sign up to request clarification or add additional context in comments.

1 Comment

This is by far the superior solution. Takes milliseconds to perform on a large data set
4

I've done it by rake script

desc 'Remove name'
  task remove_name: :environment do
    Entry.all.find_each do |entry|
      puts "Removing #{entry.id}"
      entry.data.delete("name")
      entry.save
    end
  end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.