dark_ruby
dark_ruby

Reputation: 7866

rails 3:how to generate models for existing database tables

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

Upvotes: 18

Views: 27002

Answers (5)

Glauco Roberto
Glauco Roberto

Reputation: 27

Your answer is:

$ rake db:schema:dump

That will set a new db/schema.db to create a schema of your DB.

Upvotes: 3

Boško Ivanišević
Boško Ivanišević

Reputation: 184

You can try Rmre. It can create models for existing schema and it tries to create all relationships based on foreign keys information.

Upvotes: 15

Mark Thomas
Mark Thomas

Reputation: 37517

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

Upvotes: 11

Pasted
Pasted

Reputation: 864

Could try Magic Model Generator

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160551

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.

Upvotes: 1

Related Questions