Thursday, July 30, 2015

PG::DuplicateColumn: ERROR: column already exists

Error:

PG::DuplicateColumn: ERROR:  column of relation table_name already exists

I am using Ruby On Rails with Postgresql and I faced this issue while I am doing migration.

sachin@sachin:~/demo_app$ rake db:migrate
== 20150710135824 AddStatusToUser: migrating =========================
-- add_column(:users, :status, :integer)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DuplicateColumn: ERROR:  column "status" of relation "users" already exists
: ALTER TABLE "users" ADD COLUMN "status" integer/home/sachin/.rvm/gems/ruby-2.0.0-p598@demo_app/gems/activerecord-4.1.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `async_exec'

Solution:

Error indicates that in users table status column is already available. Then I found that earlier I have added same migration and then I have done rake db:migrate that time. So That time this column is created. And now I have added again. That's why I am facing this issue.

So here solution is: We need to remove existing column and then need to do migration. 

For that I have found this ways to resolve this issue:

1.) With ruby on rails,

        Open terminal and run "rails db" command it will connect with database. Then you can drop that added columns from here.

        You need to run this command for alter table:
        ALTER TABLE users DROP COLUMN status;

2.) Open postgresql console for drop column. 
         
         Open terminal and run "psql -U postgres" command then it will open psql console.Then you can drop that added columns from here.

        You need to run this command for alter table:
        ALTER TABLE users DROP COLUMN status;

3.) Add condition in migration

        if column_exists? :table_name, :column_name
                remove_column :table_name, :column_name
        end

4 comments:

  1. oh man! you save me haha neither of the options worked until i tried the third one you gave here, thanks so much

    ReplyDelete
  2. Due on the simplicity of this form of Mortgage Calculator, many websites will include this for his or her users. mortgage payment calculator The calculator can estimate your living expenses should you not know them. canada mortgage calculator

    ReplyDelete
  3. You have shared a lot of information in this article. I would like to express my gratitude to everyone who contributed to this useful article. Keep posting. Website Reseller Hosting

    ReplyDelete