PG::DuplicateTable: ERROR: relation "posts" already exists - ruby-on-rails

When I run rake db:migrate I get following output:
== 20141219011612 CreatePost: migrating =======================================
-- create_table("posts") rake aborted! StandardError: An error has occurred, this and all later migrations canceled:
== 20141219011612 Postposts: migrating =======================================
-- create_table("posts") rake aborted! StandardError: An error has occurred, this and all later migrations canceled:
PG::DuplicateTable: ERROR: relation "posts" already exists : CREATE
TABLE "posts" ("id" serial primary key, "post" text, "release_date"
timestamp, "created_at" timestamp, "updated_at" timestamp)
/home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in
async_exec' /home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in block in execute'
/home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/connection_adapters/abstract_adapter.rb:373:in block in log' /home/admin/.rvm/gems/ruby-2.1.5/gems/activesupport-4.1.8/lib/active_support/notifications/instrumenter.rb:20:in instrument'
/home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/connection_adapters/abstract_adapter.rb:367:in log' /home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:127:in execute'
/home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/connection_adapters/abstract/schema_statements.rb:205:in
create_table' /home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/migration.rb:649:in block in method_missing'
/home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in
block in say_with_time' /home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in say_with_time'
/home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/migration.rb:641:in
`method_missing'
...
migrate' /home/admin/.rvm/gems/ruby-2.1.5/gems/activerecord-4.1.8/lib/active_record/railties/databases.rake:34:in block (2 levels) in <top (required)>' Tasks: TOP => db:migrate (See
full trace by running task with --trace)
I don't understund how this is possible, bescause In scheme file I don't have post table.

Somehow, you ended up with a table named 'posts' in your database. Perhaps from a prior migration that you deleted without rolling back? If you don't care about any of your data in the database, you can run
rake db:drop db:create db:migrate
to bring your development database inline with your current migrations.
If you have data in other tables you don't want to lose, open the database console and drop the posts table manually:
$ rails db
# drop table posts;
Then run db:migrate again.

For those who didn't get your answer above
In my case, I had been working on a feature a month ago the field happens to be created at that time. Now when I try to run migration rake db: migrate I see this error. I know and am sure that this is not here due to any mistake.
I also tried to rollback that particular migration
rake db:migrate:down VERSION=20200526083835
but due to some reason, it did nothing, and to move further I had to comment out the up method in that migration file.
# frozen_string_literal: true
class AddColToAccounts < ActiveRecord::Migration
def up
# execute 'commit;'
#
# add_column :accounts, :col, :boolean,
# null: false,
# default: false
end
def down
execute 'commit;'
remove_column :accounts, :col
end
end
And, now I am able to run the migrations.
At last, I undo the commenting thing and I am done.
Thanks

Check your db/schema.rb
You most likely have the same table being created there in addition to a migration in db/migrate/[timestamp]your_migration
You can delete the db/migrate/[timestamp]your_migration if it is a duplicate of the one found in the schema and it should work.

In case this helps anyone else, I realized that I had been using a schema.rb file that was generated while using MySQL. After transitioning to Postgres, I simply forgot I would need to run rake db:migrate before I could use rake db:schema:load

One of the hack I found was to put pry before you are creating the table on the migration file.
require 'pry'
binding.pry
create_table :your_table_name
and drop that table:
drop_table :your_table_name
After that you can remove the drop_table line and it will work fine!

kill the current postgres process:
sudo kill -9 `ps -u postgres -o pid`
start postgres again:
brew services start postgres
drop, create, and migrate table:
rails db:drop db:create db:migrate

This will delete your data, don't do it on production.
First remove the orphan migration ********** NO FILE ********** in case you have any, by executing this db command:
delete from schema_migrations where version='<MIGRATION_ID>';
then
rails db:schema:load
then
rails db:migrate
This worked for me.

I had the same problem, the only thing that worked for me was to delete the table from within the rails console, like so:
ActiveRecord::Migration.drop_table(:products)

Related

PG::UndefinedTable: ERROR: table "table-name" does not exist

I was messing with my database, creating and deleting tables. I deleted few migration files after pushing them to heroku. Previously I created a table 'moms'. Later I wanted to rename it, so I deleted 'moms' and created new table 'minutes_of_meetings'. I did $rake db:migrate and everything was done successfully and my app is running perfectly on localhost.
After pushing it to heroku, when I did $heroku run rake db:migrate, it generated the following log:
ActiveRecord::SchemaMigration Load (0.7ms) SELECT "schema_migrations".* FROM "schema_migrations"
Migrating to DropMoms (20150823142852)
(0.6ms) BEGIN
== 20150823142852 DropMoms: migrating =========================================
-- drop_table(:moms)
(0.9ms) DROP TABLE "moms"
PG::UndefinedTable: ERROR: table "moms" does not exist
: DROP TABLE "moms"
(0.5ms) ROLLBACK
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: table "moms" does not exist
: DROP TABLE "moms"/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'
/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute'
I created a new table 'moms' in heroku so that it can be deleted when migration runs. I did this:
$ heroku run Ruby console for rails-app-name >> ActiveRecord::Migration.create_table :moms
I also created a migration to create table 'moms'. But still the error persists.
EDIT:
This is my CreateMoms migration file:
class CreateMoms < ActiveRecord::Migration
def change
create_table :moms do |t|
t.string :name
t.timestamp null: false
end
end
end
When I run heroku run rake db:migrate:up
Running `rake db:migrate:up` attached to terminal... up, run.1729
rake aborted!
VERSION is required
/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/railties/databases.rake:78:in `block (3 levels) in <top (required)>'
Tasks: TOP => db:migrate:up
(See full trace by running task with --trace)
WARNING: Toolbelt v3.41.3 update available.
On heroku run rake db:migrate:down
Running `rake db:migrate:down` attached to terminal... up, run.6389
rake aborted!
VERSION is required - To go down one migration, run db:rollback
/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/railties/databases.rake:86:in `block (3 levels) in <top (required)>'
Tasks: TOP => db:migrate:down
(See full trace by running task with --trace)
WARNING: Toolbelt v3.41.3 update available.
Caution
rake db:schema:load will wipe away all of your data from the heroku database. Please make sure you have your data backup on heroku. If you already don't have backup of your heroku database, you can easily do so by using Heroku PGBackups
Looks like your schema is messed up. Just load the schema to the database using rake db:schema:load and then run the migration again:
heroku run rake db:schema:load
heroku run rake db:migrate

Why am I getting: Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development

I am a total newbie to Rails, and I am following the Railsbridge Intro to Rails. I have created my project and now I am trying to create a new controller action for voting, and a new route for voting. When I go to the development page, it shows the following message:
Migrations are pending. To resolve this issue, run: bin/rake
db:migrate RAILS_ENV=development
In the command line it gives me this information:
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `migrate' for #<ActiveRecord::ConnectionAdapters::TableDefiniti
on:0x5d79e78>C:/Sites/railsbridgejan/suggestotron/db/migrate/20150129195744_create_votes.rb:6:in `block in change' C:/Sites/railsbridgejan/suggestotron/db/migrate/20150129195744_create_votes.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
So, when I look in my db files for create_votes.rb this is what it looks like:
class CreateVotes < ActiveRecord::Migration
def change
create_table :votes do |t|
t.integer :topic_id
t.string :rake
t.migrate :db
t.timestamps null: false
end
end
end
Is there something wrong with my file's code? t.migrate :db is line 6, which according to the command line, is the problem. I am using Rails 4, Ruby 2, and Sqlite. I had tried to install MySql, but I ran into some major issues, so I just continued with Sqlite. Could that be causing this problem at all? It seems like the issue is in the code listed above, but I'm not sure.
Thank you!
Inside the change method you use
t.migrate :db
The migrate data type doesn't exist. I assume you wanted to use a String.
t.string :db

Ruby-on-Rails Tutorial Trouble

I am new to both Ruby and Rails. So this may be an easy fix. I'm sorry if it is.
I recently installed Ruby-on-Rails and started following the tutorial on rubyonrails.org which shows how to make a simple blog. Everything was running fine until I got to section 5.5. I went to run db:migrate and it gave me an error.
|D:\Documents\Programs\Ruby\blog>rake db:migrate
== 20141216061542 CreateArticles: migrating ===================================
-- create_table(:articles)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "articles" already exists: CREATE TABLE "articles" ("id" INTEGER
PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "text" text, "created_at" datetime,
"updated_at"
datetime) D:/Documents/Programs/Ruby/blog/db/migrate/20141216061542_create_articles.rb:3:in
`change
'
C:in `migrate'
ActiveRecord::StatementInvalid: SQLite3::SQLException: table "articles" already exists: CREATE
TABLE
"articles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "text" text,
"created_at" datetime, "updated_at" datetime)
D:/Documents/Programs/Ruby/blog/db/migrate/20141216061542_create_articles.rb:3:in `change'
C:in `migrate'
SQLite3::SQLException: table "articles" already exists
D:/Documents/Programs/Ruby/blog/db/migrate/20141216061542_create_articles.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
I fired up the server to see what it would show and it gave me this:
ActiveRecord::PendingMigrationError
Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development
It's been doing this ever since. I have tried starting over by deleting the project.(not entirely sure if that was a good move.) I have tried looking over the code. Nothing I have tried has given me any hints on what to do.
Is there any way to get rid of these errors?
Thank you in advance.
EDIT:
I tried to reset the database with 'rake db:reset', but it just gave me this:
|D:\Documents\Programs\Ruby\blog\app\views\articles>rake db:reset
(in D:/Documents/Programs/Ruby/blog)
Permission denied # unlink_internal - D:/Documents/Programs/Ruby/blog/db/development.sqlite3
C:/RailsInstaller/Ruby2.1.0/lib/ruby/2.1.0/fileutils.rb:1460:in `unlink'
C:/RailsInstaller/Ruby2.1.0/lib/ruby/2.1.0/fileutils.rb:1460:in `block in remove_file'
C:/RailsInstaller/Ruby2.1.0/lib/ruby/2.1.0/fileutils.rb:1468:in `platform_support'
...
rake aborted!
Errno::EACCES: Permission denied # unlink_internal -
D:/Documents/Programs/Ruby/blog/db/development.
sqlite3
Tasks: TOP => db:schema:load
(See full trace by running task with --trace)
I shortened it for readability.
And here is my create_articles migration file:
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.timestamps
end
end
end
You've already created that particular table. Try this from your terminal:
rake db:drop db:create db:migrate
Or:
rake db:reset db:migrate
So basically, you will start your database from scratch, which will avoid the current error.
Note that for new migrations, you only run the 'rake db:migrate' command otherwise your existing data will be lost.
Later on if you come across this problem in a production environment, ensure that you do 'something else' - surely you wouldn't want to sacrifice your production database data.
Well It seems obvious, you already have table articles, and you are trying to create a new one.
Two options:
comment migration with articles do rake db:migrate, uncomment for other environment (if any)
clear database and run migrations again.
Add create_articles to your question as well, could help resolving the problem.
Drop the db
rake db:drop
And Migrated it once again
rake db:migrate
You have already create articles tables. So you need to drop it and migrate it once again.

rake db:migrate not working, no errors

I'm trying to run rake db:migrate on a migration I made to drop a few columns and add a few others.
Here is the migration I'm trying to run:
class Demographics < ActiveRecord::Migration
def change
change_table :demographics do |t|
t.remove_column :demographics, :race
t.remove_column :demographics, :other_race
t.integer :race_id
t.integer :other_race_id
t.remove :demographics, :education
t.integer :education_id
t.remove :other_education
t.integer :other_education_id
end
end
end
Here is the output of: rake db:migrate status --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:migrate
** Invoke db:_dump (first_time)
** Execute db:_dump
** Invoke db:schema:dump (first_time)
** Invoke environment
** Invoke db:load_config
** Execute db:schema:dump
rake aborted!
Don't know how to build task 'status'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/task_manager.rb:49:in `[]'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:148:in `invoke_task'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:106:in `block (2 levels) in top_level'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:106:in `each'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:106:in `block in top_level'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:115:in `run_with_threads'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:100:in `top_level'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:78:in `block in run'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:165:in `standard_exception_handling'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:75:in `run'
/var/lib/gems/2.0.0/gems/rake-10.1.1/bin/rake:33:in `<top (required)>'
/usr/local/bin/rake:23:in `load'
/usr/local/bin/rake:23:in `<main>'`enter code here`
You don't need status in the migrate command:
rake db:migrate
should be enough.
You are actually getting an error from rake because of having status in the command:
rake aborted!
Don't know how to build task 'status'
EDIT
Following our discussion I now understand more.
The migration Demographics has already been applied to the database in the past. This is proved by its 14 digit datetime being included in the schema_migrations table.
Migrations are designed to be run once only. They make a change to the database (schema and/or data) and you move on.
When you run rake db:migrate it finds any migration not yet applied to the database (in datetime order from the migration filename), applies it, then puts an entry for the datatime in schema_migrations. Any migration which already has an entry in schema_migrations is ignored.
If you want to make a further change to the database - even to a table created in a previous migration - you should create a new migration, and then use bin rake db:migrate to apply it.
Yes you can backout a previously applied migration - rake db:rollback. Rollbacks will apply in the reverse order the migrations were applied, ie. working backwards from the end of schema_migrations. By default it will only back out the last migration, although you can use the STEP parameter to do more (rake db:rollback STEP=3 for example).
You can also redo a previously applied migraton - rake db:migrate:redo - again with optional STEP parameter. This is really just a shortcut for rollback followed by migrate.
RECOMMENDATION
My recommendation to you would be to put the Demographics migration file back to the way it was before you made the change. This is important in case the migrations need to be all reapplied in the future.
I would now create a new migration to apply the changes to your table:
rails generate migration UseForiegnKeysInDemographics
Make the required alterations; you only need mention the changes to the table:
e.g.
class UseForiegnKeysInDemographics < ActiveRecord::Migration
def change
remove_column :demographics, :race
remove_column :demographics, :other_race
remove_column :demographics, :education
remove_column :demographics, :other_education
add_column :demographics, :race_id, :integer
add_column :demographics, :other_race_id, :integer
add_column :demographics, :education_id, :integer
add_column :demographics, :other_education_id, :integer
end
end
And apply this new migration:
rake db:migrate
I suggest you have a read of the Rails guide on migrations; http://guides.rubyonrails.org/migrations.html as it explains everything better than my brief summary.
Footnote:
As you want to add foreign keys to the demographics table, you might want to consider add_reference instead of add_column. I didn't include this in my example above because I don't know the details of your other tables, but it's well documented in the Rails guide.
I see an issue with your command : rake db:migrate status --trace
You are trying to achieve two things with one command i.e., run the migrations as well as check the status of the migrations with the detailed steps performed.
You can do it in two ways:
1. First Way
To perform the migrations use
rake db:migrate --trace
And then check the status of all your migrations within the application, use
rake db:migrate:status
2. Alternatively
rake db:migrate db:migrate:status --trace
You almost had that but status task is within db:migrate namespace so you need to use db:migrate:status. Here, the first db:migrate will perform the pending migrations whereas db:migrate:status will give the status of all migrations and --trace will give you full backtrace.

Rails migration gives error when trying to also create a record in the self.up

I have the following migration:
def self.up
add_column :project_statuses, :system_sequence, :integer, :default => 0, :null => false
ProjectStatus.create :name => 'Declined', :sequence => 35, :system_sequence => 110
...
end
But when I do a rake db:create, rake db:migrate, I get the following error:
== NewProjectStatuses: migrating =============================================
-- add_column(:project_statuses, :system_sequence, :integer, {:default=>0, :null=>false})
-> 0.0029s
rake aborted!
An error has occurred, this and all later migrations canceled:
unknown attribute: system_sequence
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1753:in `block in assign_attributes'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `each'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `assign_attributes'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1567:in `initialize'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `new'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `create'
/[working dir]/db/migrate/20100816100139_new_project_statuses.rb:7:in `up'
The erroneous line number refers to the Project.create :name => ... line.
It seems like the add_column line isn't run at all, even though the output says it is run.
Running a rake db:migrate again runs through the migrations fine though.
Why is this?
Try calling ProjectStatus.reset_column_information after the add_column block.
Rails caches column information (including which columns exist), and I believe what you're hitting here is that you're creating a column, but that doesn't trigger Rails to reset its cache on the list of available columns. As a result, your following line fails, because it doesn't think the column exists.
I'm not sure why the caching is designed this way, but this sort of thing is explicitly mentioned in the example code regarding the use of reset_column_information. I think there's a pretty good chance that's the issue.
That being said, I also generally agree with Michael Durrant, regarding the use of filling the DB with values via migrations. The preferred method is to add your default/seed data to a rake task (which can be run at any arbitrary time), or your seeds.rb file. This is in contrast to a migration, which is only run when the current schema version is older than the specified migration.

Resources