简体   繁体   中英

ruby on rails db migration

I use mysql as the DB in my app, if I want to add a new table to it, I can either use migrate, say rails generate migration name:string age:integer

or just create a new table in mysql. Is there any difference between them two?

Yes, there is a huge difference. You should never create a table directly in the database unless you have a good reason to (such as it not directly affecting your rails app.)

If you create a table in mySQL then you will be able to access it if you create a matching model, however, when you deploy your database, you will also need to make this same change to your production database. This means that there is an extra step for deployment that could easily be forgotten. This also holds true if you have more than one person working on the project, or you are using it from more than one machine.

Another issue with creating a table directly is that your database isn't versioned. If you use migrations then you can switch between database versions at will. Did something in your migration break your application? Simple roll back to the previous version using rake db:rollback

A third implication will be that your db/schema.rb file will not reflect the database. This will prevent you from dumping your scheme at a later date. If you want to switch from say mySQL to Postgres, you will find things extremely difficult without using migrations.

When you create a table via a migration, the schema.rb file is updated to reflect the addition of the new table.

Migrations are a preferred route because you can simply run the rake task rake db:migrate and create all your tables on your development, test and production environments, rather than porting the database.

You can read more about Migrations at the official docs here - http://guides.rubyonrails.org/migrations.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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