Generate models from existing tables using Rails 3

2020-06-18 03:45发布

问题:

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?

回答1:

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


回答2:

I am no expert and even had researched about this. Without thinking to much first solution in my mind is to make the models and migrations according to the rails way so you don't have any problem, for example key and foreign key naming. If you have already some data you should migrate it to the rails db.

One reason to do this is that models are suppose not to be only data accessors but also contain the business logic