Home Keeping existing data
Reply: 1

Keeping existing data

Nelly Nelly
1#
Nelly Nelly Published in 2017-11-10 12:24:39Z

I had to create another table to extract some columns I my_tables there are many columns but a couple needed to be extracted to be used elsewhere.

So the my_new_table exists, but It doesn't have the data that I had in the columns userand guest in my_tables... So I have to rollback my migration and insert some SQL I guess? to take the data from my_tables user & guest ? How to do this please ?

class CreateMyNewTables < ActiveRecord::Migration
  def change
    create_table :my_new_tables do |t|
      t.string :user
      t.string :guest
      t.references :my_tables, index: true
      t.timestamps null: false
    end

      #how to keep the data I already have in Guest and User

    remove_column :my_tables, :guest
    remove_column :my_tables, :user

  end
end
spickermann
2#
spickermann Reply to 2017-11-10 13:47:31Z

If the tables are not too big the easiest way might be to copy the data with a few lines of Ruby code within your migration. This has the benefit of using existing associations and validation and the code is easier to read and to understand for Ruby developers.

On huge tables, I would suggest doing it in plain SQL because that would be much faster.

I assume that you have both a MyTable and a MyNewTable model.

def up
  create_table :my_new_tables do |t|
    t.string :user
    t.string :guest
    t.references :my_tables, index: true
    t.timestamps null: false
  end

  MyNewTable.reset_column_information
  MyTable.find_each do |table|
    MyNewTable.create(user: table.user, guest: table.guest, my_table: table)
  end

  remove_column :my_tables, :guest
  remove_column :my_tables, :user
end
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.353804 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO