rails 3:how to generate models for existing database tables

邮差的信 提交于 2019-11-28 19:33:19

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.

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

Glauco Roberto

Your answer is:

$ rake db:schema:dump

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

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.

Take a look at rare_map gem. https://github.com/wnameless/rare_map It works both on Rail 3 and 4.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!