Adding a column to an existing table in a Rails migration

后端 未结 11 1804
借酒劲吻你
借酒劲吻你 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:47

    To add a column I just had to follow these steps :

    1. rails generate migration add_fieldname_to_tablename fieldname:string

      Alternative

      rails generate migration addFieldnameToTablename

      Once the migration is generated, then edit the migration and define all the attributes you want that column added to have.

      Note: Table names in Rails are always plural (to match DB conventions). Example using one of the steps mentioned previously-

      rails generate migration addEmailToUsers

    2. rake db:migrate

    Or

    1. You can change the schema in from db/schema.rb, Add the columns you want in the SQL query.
    2. Run this command: rake db:schema:load

      Warning/Note

      Bear in mind that, running rake db:schema:load automatically wipes all data in your tables.

提交回复
热议问题