Brian DiCasa
Brian DiCasa

Reputation: 9487

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. For example, I have a table named person and want to generate the model based on the columns from that table. 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?

Thanks.

Upvotes: 4

Views: 6593

Answers (1)

jmcnevin
jmcnevin

Reputation: 1285

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).

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...

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.

Upvotes: 16

Related Questions