Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate 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 a couple hundred tables. We would like to try out rails to see if it would be a positive change from PHP & ZendFramework.

Migrating data into another database is not an option for us because we have several other applications currently using this database. We wanted to "attach" a rails project to the existing database.

The part I am struggling is generating all the models from our existing database.

I seen a couple of older posts talking about some automated techniques including Magic Model Generator. While others talked about there is no way to do this, or you just have create them all manually.

I was not successful in generating models using Magic Model Generator (perhaps rails 2 only?)

Long ago, when we switched to ZendFramework, I wrote a quick script to analyze the database and generate all the model files for us. It would seem this would be a somewhat common scenario.

Note: We use ID instead of id and many have many foreign_key relationships.

So I wanted to ask the community what is the best (way/practice) to handle this?

like image 514
Michael Avatar asked Mar 29 '12 18:03

Michael


1 Answers

It's not that difficult, just takes a bit more configuration. Here's a basic template for a 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
like image 57
Tanzeeb Khalili Avatar answered Nov 05 '22 10:11

Tanzeeb Khalili