在Ruby on Rails中为用户模型添加属性的最佳方法

6

我的用户模型如下:

    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

如果我想添加一个新的 :attribute,是否最好创建另一个迁移文件来添加新列(参见 Stackoverflow 线程) 或者我只需要手动添加 t.string :name_of_new_attribute 并运行 rake db:migrate?谢谢!
1个回答

16

正确的方法是创建一个新的迁移。在主要的rails项目文件夹中运行:

rails generate migration AddDetailsToUser address:string age:integer 等等...

然后运行 rake db:migrate

另一种方法是编辑原始的迁移文件,重置/销毁数据库并重新运行所有迁移。


那么,如果我将来想添加更多属性,我可以简单地编辑这个迁移文件吗? - Elias7
7
最好创建另一个迁移来包含新属性。 - Norto23

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接