Rails 3:如何为现有数据库表生成模型
我已将 database.yml 配置为指向现有的 mysql 数据库,
如何从中生成模型?
rails generate model existing_table_name
只给出一个空模型..
I've configured my database.yml to point to my existing mysql database
how can I generate models from it?
rails generate model existing_table_name
only gives an emty model..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以尝试 Rmre。它可以为现有模式创建模型,并尝试根据外键信息创建所有关系。
You can try Rmre. It can create models for existing schema and it tries to create all relationships based on foreign keys information.
Rails 模型不会显示您的字段,但您仍然可以使用它们。尝试以下操作。假设您有一个名为 ModelName 的模型和一个名为“name”的字段,请启动 Rails 控制台并输入:
给定数据库中存在的名称,您应该会看到结果。
尽管 Rails 不会推断关系,但如果您的数据库遵循 Rails 约定,则可以轻松添加它们。
更新
我注意到这种特定的缺乏明确性(“魔力”)是 Rails 新手感到困惑的一个根源。您始终可以在
schema.rb
中查看模型和所有字段。此外,如果您希望查看模型文件中每个模型的架构,可以使用 annotate_models gem,它将把数据库模式放在模型文件顶部的注释中。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:
Given a name that exists in the DB, you should see results.
Rails doesn't infer relationships though, but if your database follows Rails conventions they are easily added.
Update
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.您的答案是:
这将设置一个新的
db/schema.db
来创建数据库的模式。Your answer is:
That will set a new
db/schema.db
to create a schema of your DB.ActiveRecord 不解析架构定义。它向 DBM 询问表定义并即时计算出字段。
如果您要通过迁移修改表,那么拥有架构会很有用。
架构转储和你
会有所帮助您将其转储以用作构建迁移的参考。ActiveRecord 对表命名做出一些假设,并期望 id 字段作为主键,并以序列号作为类型。进行迁移将帮助您重构表和/或字段名和类型,但您可以通过 DBM 的命令行执行相同的操作。您实际上不必遵循 ActiveRecord 的风格,但这样做有助于避免奇怪的错误,并让 AR 推断事物以使您的生活更轻松。
ActiveRecord doesn't parse a schema definition. It asks the DBM for the table defs and figures out the fields on the fly.
Having the schema is useful if you are going to modify the tables via migrations.
Schema Dumping and You
will help you dump it to use as a reference for building migrations.ActiveRecord makes some suppositions about the table naming and expects an
id
field to be the primary key with a sequential number as the type. Having the migrations would help you to refactor the tables and/or fieldnames and types, but you can do those same things via your DBM's command-line. You don't really have to follow ActiveRecord's style but doing so helps avoid odd errors and lets AR infer things to make your life easier.可以尝试魔法模型生成器
Could try Magic Model Generator
看看rare_map gem。
https://github.com/wnameless/rare_map
它适用于 3 号线和 4 号线。
Take a look at rare_map gem.
https://github.com/wnameless/rare_map
It works both on Rail 3 and 4.