rails 3:如何为现有数据库表生成模型

编程入门 行业动态 更新时间:2024-10-26 18:24:17
本文介绍了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:如何为现有数据库表生成模型

本文发布于:2023-10-20 01:14:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509391.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为   模型   数据库   rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!