Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how remove an element from json string column by activerecord

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"}
like image 349
Mini Avatar asked Jul 26 '17 15:07

Mini


2 Answers

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

like image 181
Jose Elera Avatar answered Oct 14 '22 04:10

Jose Elera


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
like image 2
Mini Avatar answered Oct 14 '22 04:10

Mini