简体   繁体   English

Rails从现有表生成模型?

[英]Rails Generate Model from Existing Table?

I'm very new to the rails framework and want to know how to generate a model based on an existing table. 我是rails框架的新手,想知道如何基于现有表生成模型。 For example, I have a table named person and want to generate the model based on the columns from that table. 例如,我有一个名为person的表,并希望根据该表中的列生成模型。 However, whenever I use "ruby script/generate model Person --skip-migration it creates an empty table named people and creates the model after that. Is there a way to generate a model after a table named person? 但是,每当我使用“ruby脚本/生成模型Person --skip-migration时,它会创建一个名为people的空表并在此之后创建模型。有没有办法在名为person的表之后生成模型?

Thanks. 谢谢。

Rails is very opinionated, so if you have a table called "person" and you want the corresponding model to be called Person, you need to tell Rails explicitly not to be so clever (otherwise, it will assume that it needs to look for the plural of the model name for the table name). Rails很自以为是,所以如果你有一个名为“person”的表,并且你希望相应的模型被称为Person,你需要明确告诉Rails不要这么聪明(否则,它会假设它需要寻找表名的多个模型名称)。

class Person < ActiveRecord::Base
  set_table_name 'person'
end

If your table's primary key isn't called "id", then you'll need to specify that, too... 如果你的表的主键没有被称为“id”,那么你也需要指定它...

set_primary_key 'person_id'

You may also need to specify a different autoincrement sequence name, depending on your database. 您可能还需要指定不同的自动增量序列名称,具体取决于您的数据库。

There's not a way that I know of to automatically generate a model from an existing legacy table, but this should get you most of the way there. 我不知道如何从现有的遗留表中自动生成模型,但这应该可以帮助您完成大部分工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM