Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a column to an existing table in a Rails migration

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 t.string :email, did rake db:migrate, and got a NoMethodError. Then I added the line

add_column :users, :email, :string 

again rake db:migrate, again NoMethodError. Am I missing a step here?

Edit: here's the migration file.

class CreateUsers < ActiveRecord::Migration     def self.up       add_column :users, :email, :string       create_table :users do |t|         t.string :username         t.string :email         t.string :crypted_password         t.string :password_salt         t.string :persistence_token          t.timestamps       end     end      def self.down       drop_table :users     end   end 
like image 949
John Avatar asked Jan 29 '11 02:01

John


People also ask

Can you edit a migration file rails?

Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.

How do I add a field to a model in Rails?

Normally, you first have to extend the data model. This task is simplified by using rails generate migration and rake db:migration . Note that you may prefer to use rake with bundle exec to ensure to use the version of rake in your Gemfile.


2 Answers

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).

like image 70
Dylan Markow Avatar answered Nov 14 '22 02:11

Dylan Markow


Use this command on the terminal:

rails generate migration add_fieldname_to_tablename fieldname:string 

and

rake db:migrate 

to run this migration

like image 44
vinodh Avatar answered Nov 14 '22 01:11

vinodh