1

I currently have the migrate thing like:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :encrypted_password
      t.string :salt

      t.timestamps
    end
  end
end

now, if I wanna add two new attributes into this file, one is: t.string :type , and the other one is: t.string :memory_token , how can I do this please?

zzx
  • 179
  • 2
  • 12

2 Answers2

3

If you have already run the migration you will have to create a new one.

rails g migration AddTypeToUsers

And then in the migration file you can edit in

change_table :users do |t|
  t.string :type
  t.string :memory_token
end

Then run a migration rake db:migrate to make the changes

If you haven't run the migration then you can simply add

  t.string :type
  t.string :memory_token

To that file you have showed us and then run your migration

JTG
  • 8,587
  • 6
  • 31
  • 38
  • I'm not sure I understand. The commands I showed you will generate a *brand new* migration file, which is your best option if you have already run `rake db:migrate` on this migration file. If you haven't run `rake db:migrate` you can simply edit the current migration file and no harm will come. – JTG Jul 23 '14 at 22:43
  • Let's simplify this. Have you run the migration? you can check by `rake db:migrate:status` – JTG Jul 23 '14 at 22:45
  • i did run rake db:migrate already before I posted this question, and can i just simply vim the migrate file to add these new attributes into it? – zzx Jul 23 '14 at 23:41
  • No, because you've already run the migration. Rails remembers the files of migrations it has already ran and will not run them again. You need to start a new migration. You can either follow my instructions or @IIya's instructions, both will give you the outcome you want (adding type and memory_token strings to the users table) – JTG Jul 24 '14 at 03:03
2

+1 to @JTG

You can also make this just with one line:

rails g migration AddTypeAndMemoryTokenToUsers type:string memory_token:string

and you will get a following file:

class AddTypeAndMemoryTokenToUsers < ActiveRecord::Migration
  def change
    add_column :users, :type, :string
    add_column :users, :memory_token, :string
  end
end

which will make the changes after running rake db:migrate

Ilya
  • 121
  • 2
  • 7