Export and import/restore data for one table using ActiveRecord from Rails console

Export and import/restore data for one table using ActiveRecord from Rails console

your_model = User
column_names = your_model.column_names - ['created_at', 'updated_at'] # we can ignore some unimportant fields
backup_array = []
your_model.find_each(batch_size: 500) do |your_record|
  p_hash = {}
  column_names.each do |col_name|
    p_hash.merge!("#{col_name}" => your_record.send(col_name))
  end
  backup_array << p_hash
end

This will create an array of hashes like this:

{"id"=>2, "column_1"=>3, "column_2"=>4, "colum_3"=>"heriberto@example.com""}

In case that something goes wrong you can restore your data doing something like this:

backup_array.each do |record_hash|
  find_record = your_model.find(record_hash['id'])
  puts "========== id #{find_record.id} =========="
  new_attributes = record_hash.except('id')
  find_record.update_columns(new_attributes)
end

As always keep reading, coding and relax

No Comments

Post A Comment