Rails-了解db:migrate [英] Rails -- understanding db:migrate

查看:141
本文介绍了Rails-了解db:migrate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解Ruby on Rails中的迁移时遇到了一些麻烦。我的应用程序的 db\migrate\ 目录中有以下两个类(存储在单独的文件中):

I am having a little trouble understanding migrations in Ruby on Rails. I have the following two classes in my application's db\migrate\ directory (stored in separate files):

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

class AddEmailUniquenessIndex < ActiveRecord::Migration
  def self.up
    add_index :users, :email, :unique => true
  end

  def self.down
    remove_index :users, :email
  end
end

我对这两个文件似乎如何一起运行感到困惑。创建第二个类后,Michael Hartl的书说:我们可以为 users 表编辑迁移文件,但这需要先回滚然后再进行迁移。Rails方式是每次都使用迁移我们发现我们的数据模型需要改变。这些迁移实际上如何工作?迁移数据库时目录中的所有文件都运行吗?就像这里幕后发生的事情一样?

I am confused at how these two files seem to be run together. Upon creation of this second class, Michael Hartl's book says "we could just edit the migration file for the users table but that would require rolling back then migrating back up. The Rails Way is to use migrations every time we discover that our data model needs to change." How do these migrations actually work? Are all the files in the directory run when the database is migrated? Like what is going on behind the scenes here??

推荐答案

按照惯例,这些迁移类的文件名将以前缀创建时间的时间戳表示形式(例如20110611000000)。当您运行db:migrate时,rails将检查数据库中的特殊表,该表包含上一次应用于数据库的迁移的时间戳。然后,它将在该日期之后应用带有时间戳的所有迁移,并使用上一次迁移的时间戳更新数据库表。结果,每个迁移类都只应用到数据库一次。

As convention, the file name for these migration classes will be prefixed by a timestamp representation of when these were created (ex. 20110611000000). When you run db:migrate, rails will check a special table in the database which contains the timestamp of the last migration applied to the database. It will then apply all of the migrations with timestamps after that date and update the database table with the timestamp of the last migration. As a result, each migration class is applied exactly once to the database.

Michael Hart说明,如果将所有迁移都放在一个文件中,Rails将会拥有艰难/不可能的时间,告诉哪些迁移已应用,哪些没有应用。此时唯一的选择是删除数据库中的所有表,并从头开始进行所有迁移。从功能上讲可以,但是您会丢失所有数据。最好只朝前进方向移动,而不是回到起点然后再向前移动。

Michael Hart was illustrating that if you put all of the migrations into a single file, rails would have a hard / impossible time telling which migrations had been applied and which ones hadn't. The only option at that point would be to drop all the tables in the database and run through all the migrations from the beginning. Functionally that works, but you would lost all your data. Better to move only in the 'forward' direction than back to the beginning and then forward again.

这篇关于Rails-了解db:migrate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆