Adding a column to an existing table in a Rails migration

后端 未结 11 1769
借酒劲吻你
借酒劲吻你 2020-11-28 00:34

I have a Users model which needs an :email column (I forgot to add that column during the initial scaffold).

I opened the migration file and added

相关标签:
11条回答
  • 2020-11-28 00:54

    Use this command at rails console

    rails generate migration add_fieldname_to_tablename fieldname:string
    

    and

    rake db:migrate
    

    to run this migration

    0 讨论(0)
  • 2020-11-28 00:55

    You can also force to table columns in table using force: true, if you table is already exist.

    example:

    ActiveRecord::Schema.define(version: 20080906171750) do
      create_table "authors", force: true do |t|
        t.string   "name"
        t.datetime "created_at"
        t.datetime "updated_at"
      end
    end
    
    0 讨论(0)
  • 2020-11-28 00:59

    When I've done this, rather than fiddling the original migration, I create a new one with just the add column in the up section and a drop column in the down section.

    You can change the original and rerun it if you migrate down between, but in this case I think that's made a migration that won't work properly.

    As currently posted, you're adding the column and then creating the table.

    If you change the order it might work. Or, as you're modifying an existing migration, just add it to the create table instead of doing a separate add column.

    0 讨论(0)
  • 2020-11-28 01:00

    You could rollback the last migration by

    rake db:rollback STEP=1
    

    or rollback this specific migration by

    rake db:migrate:down VERSION=<YYYYMMDDHHMMSS>
    

    and edit the file, then run rake db:mirgate again.

    0 讨论(0)
  • 2020-11-28 01:01

    You can also do

    rake db:rollback
    

    if you have not added any data to the tables.Then edit the migration file by adding the email column to it and then call

    rake db:migrate
    

    This will work if you have rails 3.1 onwards installed in your system.

    Much simpler way of doing it is change let the change in migration file be as it is. use

    $rake db:migrate:redo
    

    This will roll back the last migration and migrate it again.

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