使用Rails 3从现有表生成模型 [英] Generate models from existing tables using Rails 3

查看:255
本文介绍了使用Rails 3从现有表生成模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Rails 3.2.2 ruby​​ 1.9.3dev 和mysql



我是ruby和rails的新人。我们有一个有几百个表的现有数据库。我们想试试rails,看看是否会是一个积极的变化从PHP& ZendFramework。



将数据迁移到另一个数据库不是我们的选择,因为我们有其他几个应用程序正在使用此数据库。我们希望将rails项目附加到现有数据库。



我努力的部分是从现有数据库生成所有模型。



我看到一些旧的帖子谈论一些自动化技术,包括魔法模型生成器



我没有成功地使用Magic Model Generator生成模型(也许是rails



很久以前,当我们切换到ZendFramework时,我写了一个快速脚本来分析数据库并为我们生成所有模型文件。



注意:我们使用 ID 而不是 id ,并且有很多 foreign_key 关系。



社区什么是最好的(方式/实践)来处理这个?

解决方案

这不是那么困难,只是需要一点组态。下面是一个模型的基本模板:

  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


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?

解决方案

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

这篇关于使用Rails 3从现有表生成模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆