Creating models from existing tables using Rails 3

Using Rails 3.2.2 and ruby 1.9.3dev and mysql

I am new to ruby ​​and rails. We have an existing database with several hundred tables. We would like to try the rails to see if this will be a positive change from PHP and ZendFramework.

Migrating data to another database is not an option for us, since we are currently using this database. We wanted to β€œattach” a rails project to an existing database.

The part I'm struggling with spawns all the models from our existing database.

I saw a couple of old posts talking about some automated methods, including the Magic Model Generator . While others said that there is no way to do this, or you just created them all manually.

I was unable to create models using the Magic Model Generator (maybe only rails 2)

Once upon a time, when we switched to ZendFramework, I wrote a quick script to analyze the database and create all the model files for us. It would seem that this will be a somewhat common scenario.

Note. We use ID instead of ID , and many of them have many foreign_key relationships.

So, I wanted to ask the community which is better (way / practice) to handle this?

+6
source share
2 answers

It's not that complicated, just a little more tweaking is required. Here is the basic template for the model:

 class YourIdealModelName < ActiveRecord::Base self.table_name = `actual_table_name` self.primary_key = `ID` belongs_to :other_ideal_model, :foreign_key => 'foreign_key_on_other_table' has_many :some_other_ideal_models, :foreign_key => 'foreign_key_on_this_table', :primary_key => 'primary_key_on_other_table' end 
+2
source

I am not an expert and have not even researched about it. Without thinking that the first solution in my head is to make models and migrations in accordance with the rails so that you do not have problems, for example, with the names of key and foreign keys. If you already have data, you should transfer it to db rails.

One of the reasons for this is that models involve not only access to data, but also business logic.

0
source

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


All Articles