Best way to import data into a new rails application?

Hi I have a sqlite3 database full of data from my previous version of a web application that is NOT written on rails. Im now rewrite the web application in rails from scratch. But Id like to use the data from my previous application in the new rails application. What is the best way to do this?

This is what Ive tried so far, and it did not work very well: 1) I created a new rails application

2) replaced my sqlite3 database in the new application with sqlite3 database from the old application

3) Created a model with the same scheme as the old database.

4) changed the databse.yml file with the updated DB file data.

5) The method "set_connection" is added in my model

6) I could make him show me all the details of the old database in my browser @ "index.html"

7) However, I had problems inserting / editing records in the database. Since the database did not have a primary key column for each row, it did not work.

8) So, I tried to migrate to add a column with a primary key. He did not work

9) unexpectedly, a new development.sqlite3 database appeared in the application, and she tried to add a primary key to the NEW DB.

10) So, I just deleted the new database that popped up, and after that the application did not work

11) Now I want to start from scratch, and therefore my question is: "The best way to import data from a previous application without rails (in DB sqlite3 format) into a new application" rails "

+4
source share
1 answer

You want to work with 2 databases, old and new. So your database.yml should have 2 connections in it. There should be your normal connection, called development or production, and the other should be called obsolete. Fill in their other connection information. By default, your ActiveRecord models will be retrieved from one unnamed heritage.

Create a model called LegacyBase. In the model put establish_connection "legacy" . Now create a directory in app / models / legacy. Place all models as data from the old database inside this directory. All of these models should extend from LegacyBase. This will mean that they are all reading from the old database.

Create your new models. Do you want them to have a primary key column? If not, see this answer. Create an ActiveRecord database table without id: column . By default, they will have an identifier column, and I recommend leaving it that way.

For each of the legacy models, write a method called to_model. In this method, write code that creates a new object and fills it with old data and saves it. Something like that:

 class OldUser < LegacyBase establish_connection "legacy" def to_model User.create!(self.attributes) end end 

You can make any logic that needs to happen so that the old data matches your new application. Call this method for all old entries, such as OldUser.all.map(&:to_model) .

Do this for all the tables you want to move.

+5
source

Source: https://habr.com/ru/post/1400739/


All Articles