Search code examples
databaseruby-on-rails-4plsqlrails-migrations

How to migrate my database backup which is in ".txt" file to my new Rails App?


As of now, I'm a newbie to Rails. I'm planned to develop a new Rails application for my practice.

I have a DB backup in .TXT file format and I would like to use that database in my new application.

But, I don't know how to Migrate that DB which was in .TXT format in my new Rails Application.


Solution

  • If you have those values separated by comma(,), you could use CSV to import them to your new rails database. Put your file in a directory under db, in the following example I called 'data'. You must edit the file seeds.rb that lies in your db directory and put something like this:

    require 'csv'
    
    CSV.foreach(Rails.root.join("db/data/<yourfile>.csv"), encoding: "ISO-8859-1", headers: true, col_sep: ";") do |row|
    
    <Your rails model>.find_or_create_by(<attribute1>: row[0], <attribute2>: row[1], <attribute3>: row[2])
    
    end
    

    In the "encoding" you must put the enconding used when the txt file was created. The "headers" tells the importer that the first line of your file have the columns name, put false if your file doesn't have this. And "col_sep"is the separator between each value in your file, in my case it was a semicolon.

    If you are importing client data, for instance, and you have a model called Client with first_name, last_name and client_code as attributes your code would look like this:

    Client.find_or_create_by(first_name: row[0], last_name: row[1], client_code: row[2])
    

    Your file must be in the format like this:

    FIRST_NAME, LAST_NAME, CLIENT_CODE John, Smith, 1234 Linda, Hartl, 4321

    If you have more "columns"you will continue to put attributes and rows, like this:

    attribute_n: row[n],

    If you don't have your data comma separated, you can import the TXT to file to excel and then save the file with imported data as .CSV.