I've configured my database.yml to point to my existing mysql database
how can I generate models from it?
rails generate model exist开发者_StackOverflow中文版ing_table_name
only gives an emty model..
You can try Rmre. It can create models for existing schema and it tries to create all relationships based on foreign keys information.
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.
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.
Could try Magic Model Generator
Take a look at rare_map gem. https://github.com/wnameless/rare_map It works both on Rail 3 and 4.
精彩评论