Adding A Column To An Existing Table In A Rails Migration
Answer :
If you have already run your original migration (before editing it), then you need to generate a new migration (rails generate migration add_email_to_users email:string
will do the trick). It will create a migration file containing line: add_column :users, email, string
Then do a rake db:migrate
and it'll run the new migration, creating the new column.
If you have not yet run the original migration you can just edit it, like you're trying to do. Your migration code is almost perfect: you just need to remove the add_column
line completely (that code is trying to add a column to a table, before the table has been created, and your table creation code has already been updated to include a t.string :email
anyway).
Use this command at rails console
rails generate migration add_fieldname_to_tablename fieldname:string
and
rake db:migrate
to run this migration
Sometimes rails generate migration add_email_to_users email:string
produces a migration like this
class AddEmailToUsers < ActiveRecord::Migration[5.0] def change end end
In that case you have to manually an add_column
to change
:
class AddEmailToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :email, :string end end
And then run rake db:migrate
Comments
Post a Comment