代码之家  ›  专栏  ›  技术社区  ›  Kevin Pang

Rails/迁移中的模型更新

  •  7
  • Kevin Pang  · 技术社区  · 14 年前

    Let's say I used the following command to create a "User" model:

    script/generate model User username:string
    

    This creates the user.rb file along with the migration rb file to create the Users table. Now, I want to add an email column to my User model. What's the best way to do that? Do I do it manually and write the migration file by hand or is there a shortcut for doing it? If I write the migration by hand, do I have to name it the same way as the previous migration script (with a timestamp in front) to guarantee that it runs after the previous migration?

    3 回复  |  直到 7 年前
        1
  •  6
  •   Garfield    14 年前

    不要担心时间戳。它将自动生成。 你可以做

    script\generate migration add_email_to_user email:string
    

    This would automatically create a migration file which would look like this:

    class AddEmailToUser < ActiveRecord::Migration
      def self.up
        add_column :email, :string
      end
    
      def self.down
        remove_column :email
      end
    end
    

    该文件将具有格式的时间戳。 YYYYMMDDHHMMSS (For Rails 2.1 and above) appended in front of the filename.

        2
  •  2
  •   Bryan Ash    14 年前

    这个 Guide has information about generating migrations. If you use the rails generator, it will create correctly named files:

    ruby script/generate migration AddEmailToUser email:string
    
        3
  •  1
  •   Jey    14 年前

    Well you can do two things:

    1) If you haven't deployed this anywhere yet, or you don't mind dumping the db and running your migrations again, then modify the file. 从数据库中删除表,然后运行db:migrate。Easy to do this in development.

    2)如果此应用程序正在生产,或者您不想删除所有表。然后创建一个新的迁移文件。然后在这个新的迁移中添加/修改/删除列。然后运行db:migrate,新的更改将在表中生效。这是最佳实践。

    至于命名迁移,使用时间戳是因为Rails将创建一个跟踪最近运行的迁移的表。为此,最好使用时间戳。但是如果您选择,您可以使用自己的约定而不是时间戳。Maybe name them 001_migration.rb, 002_migration.rb, etc.

    Hope that helps.