Rails - Generating migration script from model

前端 未结 2 1002
我寻月下人不归
我寻月下人不归 2021-02-20 18:40

I am learning rails, and I came across Migrations. It seems that everytime I want to edit a model, I would need to add a migration script, even though I am not yet in production

相关标签:
2条回答
  • 2021-02-20 19:06

    If your using rails 3+ you might want to consider DataMapper instead of ActiveRecord. It lets you define the data model in the model instead of multiple migration files. As I understand DataMapper lets you generate migrations from changes.

    This is a tried and trusted pattern often used in the wider ORM community.

    0 讨论(0)
  • 2021-02-20 19:13

    I agree with the comments so far. The idea of migrations is to make it simple to fluidly adapt your data schema to fit your application as you want to add new fields. It's a simple and beautiful system.

    So yes, you can (and should) use rails generate migration... as not only does this generate the proper code in many common cases, it also keeps track of which migrations have been run in different versions of the database. See http://guides.rubyonrails.org/migrations.html#creating-a-migration

    A common workflow might be something like this:

    • create a new model, for example User with fields like first_name, last_name, user_name
    • this will create an associated migration, which you can run using bundle exec rake db:migrate -- your database schema will be updated
    • you decide you want additional information, such as birthdate, so run rails generate migration AddBirthdateToUser birthdate:date. For some simple operations like adding a column, index, etc., the full migration code will be generated; in other cases you'll need to write the migration. When done, run the migration.
    • If you find a problem in development, for example a field type should be float, not integer, or you forgot to add an index, you can roll back the migration (bundle exec rake db:rollback), fix the migration and re-run it.
    • run your tests (which will run the migrations), and when it all works for you locally, check in the files (including the migrations) and deploy to a QA or staging server, which has its own copy of the database.
    • run rake db:migrate on the staging server. If you're on a team and other developers have checked in migrations, their will run, too. Now your code and data schema are in sync.
    • repeat :-)

    There's no harm whatsoever running migrations during a production deployment (I respectfully disagree with a comment above) -- you should embrace the idea that change, even changes like this (which can be incredibly difficult in other environments) are a normal part of everyday Rails life!

    0 讨论(0)
提交回复
热议问题