rails 3:如何为现有数据库表生成模型 [英] rails 3:how to generate models for existing database tables

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

问题描述

我已经将我的 database.yml 配置为指向我现有的 mysql 数据库

I've configured my database.yml to point to my existing mysql database

如何从中生成模型?

rails generate model existing_table_name

只给出一个空模型..

推荐答案

Rails 模型不显示您的字段,但您仍然可以使用它们.请尝试以下操作.假设您有一个名为 ModelName 的模型和一个名为name"的字段,启动 Rails 控制台并输入:

A Rails model doesn't show your fields, but you can still use them. Try the following. Assuming you have a Model named ModelName and a field called "name", fire up the Rails console and type:

ModelName.find_by_name('foo')

给定数据库中存在的名称,您应该会看到结果.

Given a name that exists in the DB, you should see results.

Rails 不会推断关系,但如果您的数据库遵循 Rails 约定,它们很容易添加.

Rails doesn't infer relationships though, but if your database follows Rails conventions they are easily added.

更新

我注意到这种特别缺乏明确性(神奇")是 Rails 新手感到困惑的根源.您可以随时查看 schema.rb 以在一处查看模型和所有字段.此外,如果您希望在模型文件中查看每个模型的架构,您可以使用 annotate_modelsgem,它将把数据库模式放在模型文件顶部的注释中.

I've noticed this particular lack of explicitness ("magic") is a source of confusion for newbies to Rails. You can always look in schema.rb to see the models and all the fields in one place. Also, if you would prefer to see the schema for each model in the model file, you can use the annotate_models gem, which will put the db schema in a comment at the top of the model file.

这篇关于rails 3:如何为现有数据库表生成模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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