Miguel Angel Quintana
Miguel Angel Quintana

Reputation: 1399

Fixing migration error

I tried to create a migration to add roles to my user tables but i accidentally typed AddRolesToUsers instead of AddRoleToUser. So i tried creating a new migration with the correct AddRoleToUsers but when i tried to run rake db:migrate i got an error :

SQLite3::SQLException: duplicate column name: role: ALTER TABLE "users" ADD "role" integer/Users/miguel/.rvm/gems/ruby-2.2.1/gems/sqlite3-1.3.11/lib/sqlite3/database.rb:91:in `initialize' 

I tried rake db:migrate:down VERSION= do delete the one I had to type on but i keep getting the same error . PS: i deleted the migration file manually after running rake db:migrate:down VERSION=

rails g migration AddRoleToUsers role:integer

migration file :

class AddRoleToUsers < ActiveRecord::Migration
  def change
    add_column :users, :role, :integer
  end
end

Upvotes: 0

Views: 671

Answers (2)

Cent
Cent

Reputation: 881

When you ran the first migration, the role column was added to the Users table. The error on the second migration tells you that much.

To clear the migration pending error, you need to comment out the add_column statement in the new migration. i.e,

class AddRoleToUsers < ActiveRecord::Migration
  def change
    # add_column :users, :role, :integer
  end
end

Then run the migration. This way, the new migration should run successfully.

You can now uncomment it and delete the previous migration, so that when you deploy, only the newer migration is run and the role column is added successfully.

Upvotes: 1

RuNpiXelruN
RuNpiXelruN

Reputation: 1920

In that case right click and delete both migration files and start again. The error exists because it thinks you want to add two columns both named role to your users table

UPDATE

In that case, if role already exists in your users table, a migration must've been successfully run and there is no need to run another. As long as the role column is there, trying to add another column called role will always give you an error. If you wanted to test that you are still able to add new columns you can always check by creating a test migration AddSomethingToUsers something:string and rake db:migrate to test, then rake db:rollback to undo..but it all seems like it's worked so I probably my wouldn't mess with it too much.

Upvotes: 0

Related Questions