新手问题 Rails 如何对已有的数据表建立相应的 Model?

dume2007 · October 21, 2013 · Last by ericguo replied at October 22, 2013 · 5964 hits

现在我有个数据库,20 几个表,以前是用于 php 的,现在想用 RoR 试着重写,现在的问题是如何通过这些已有的表建立相应的模型呢?像命令: rails generate model Product name:string description:text

可能跟我已有表的字段类型有些匹配不起来,长度也不一样,这个该如何解决?

Reverse engineering... 这时候就无比的怀念 hibernate。

试试这个:https://github.com/bosko/rmre

现成的数据库根本不用 generate

class Product < ActiveRecord::Base
end

就行了。

我想,这个大概是你想要的

class YourModel < ActiveRecord::Base
     set_table_name 'your_table_name'
 end

导出当前的 schema

rake db:schema:dump         # Create a db/schema.rb file that can be portably used against any DB supported by AR

#4 楼 @oldfritter set_table_name +1

嗯 我用了 2 楼 Reverse engineering 工具生成的也是#4 楼 @oldfritter 产生的格式~

@dume2007 ,这个估计你能用上 指定此使用 mydatabase 这个 database 中的 your_model 表

class YourModel < ActiveRecord::Base
  establish_connection :mydatabase
end

database.yml 中加上

mydatabase:
  adapter: mysql
  encoding: utf8
  collation: utf8_general_ci
  reconnect: false
  database: mydatabase
  username: root
  password: root
  host: localhost

会有很多坑的,比如原来的表中用了一些在 Rails 中有特殊意义的字段;如果可以的话,重新建数据库导入数据也无妨。

@hbin 现实情况很多是不允许改的,然后就是看程序员处理这些坑的能力了

#11 楼 @oldfritter 一些老系统的数据库设计用了很多约束,也不够 Rails,用 factory_girl 之类的写测试也不方便,可以试试 machinist

正巧也在做类似的,AR 其实也是支持反向工程的,看你怎么用啦,二楼的rmre没用过,我都是手写 model 的。。

class EicKgdtestprogram < ActiveRecord::Base
    self.table_name = 'f_kgdprodprog'
    establish_connection("eic")
    default_scope -> { where flag: 1 }
    def readonly?
        true
    end
    belongs_to :productbase, :primary_key => "prod_id", :foreign_key => "productname"
end
class Productbase < ActiveRecord::Base
# 这个可以是正常表
end
You need to Sign in before reply, if you don't have an account, please Sign up first.