I saw this question up before, but only for rspec. I haven't created test yet because it's too advanced for me but one day soon i will! :P
I get this error when I try to sign-up/login into my app. I used devise to create user and also omniauth2 to sign-in with google.
this is the error
ActiveRecord::StatementInvalid at /users/auth/google_oauth2/callback
PG::UndefinedTable: ERROR: relation "users" does not exist
LINE 5: WHERE a.attrelid = '"users"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"users"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
I tried rake db:migrate, but it already is created: in schema table users exist. Has anyone got this error before?
database.yml
config=/opt/local/lib/postgresql84/bin/pg_config
development:
adapter: postgresql
encoding: unicode
database: tt_intraweb_development
pool: 5
username: my_username
password:
test:
adapter: postgresql
encoding: unicode
database: tt_intraweb_test
pool: 5
username: my_username
password:
production:
adapter: postgresql
encoding: unicode
database: tt_intraweb_production
pool: 5
username: my_username
password:
At first, you shall detach all connections out of database. By default you use the development environment. Then try to reset database with the following:
rake db:reset
The rake db:reset task will drop the database and set it up again. This is functionally equivalent to rake db:drop db:setup.
This is not the same as running all the migrations. It will only use the
contents of the current schema.rb file. If a migration can't be rolled back,
rake db:reset may not help you. To find out more about dumping the schema see
Schema Dumping and You section. Rails Docs
If the trick doesn't help, drop the database, then re-create it again, migrate data, and if you have seeds, sow the database:
rake db:drop db:create db:migrate db:seed
or in short way (since 3.2):
rake db:migrate:reset db:seed
Since db:migrate:reset implies drop, create and migrate the db. Because the default environment for rake is development, in case if you see the exception in spec tests, you should re-create db for the test environment as follows:
RAILS_ENV=test rake db:drop db:create db:migrate
or with just loading the migrated scheme:
RAILS_ENV=test rake db:drop db:create db:schema:load
In most cases the test database is being sowed during the test procedures, so db:seed task action isn't required to be passed. Otherwise, you shall to prepare the database (this is deprecated in Rails 4):
rake db:test:prepare
and then (if it is actually required):
RAILS_ENV=test rake db:seed
On newer versions of Rails the error ActiveRecord::NoEnvironmentInSchemaError may be risen, so just prepend the tasks with a database environment set task: db:environment:set:
RAILS_ENV=test rake db:environment:set db:drop db:create db:migrate
I encountered this error, and upon my research, found out that one of the reasons for PG undefinedtable error relation users does not exist error is:
This error is a migration error. You may have created new model with some database attributes. After creating model you have to migrate attributes to your rails app schema.
If you are using local machine, for development, you can use command
rake db:migrate
If you're using heroku
heroku run rake db:migrate
Your test database is not ready for rspec.
Prepare your test database for rspec to fix this error
RAILS_ENV=test rake test:prepare
It will drop, create and add migrations to your test database
In case rake task is aborted with message like 'PG::Error: ERROR: database "[your_db_test]" is being accessed by other users' execute this one
RAILS_ENV=test rake db:migrate
I was getting this error as well when running rspec:
Failure/Error: it { expect(subject.priority_list).to eq [nil] * 9 }
ActiveRecord::StatementInvalid:
PG::UndefinedTable: ERROR: relation "priorities" does not exist
LINE 5: WHERE a.attrelid = '"priorities"'::regclass
...
It was resolved for me after I ran
rake db:test:prepare
rake db:test:load
I had a similar error. The root of my error was that I had a reference to a Rails model in my factories.rb file. So it caused a load error issue. The fix was to wrap the reference in a block or {} so that it delays running it.
Here was the BROKEN code:
FactoryGirl.define do
factory :user do
guid User.new.send(:new_token)
end
end
And it was erroring because User was not defined when factories.rb was being loaded. I wrapped the User.new call in a block and it solved the issue:
Fixed code:
FactoryGirl.define do
factory :user do
guid { User.new.send(:new_token) }
end
end
Note: probably not best practice to need to call your model like this, but it was a solution to DRY up my code.
This is often caused by a bug in ActiveAdmin. Here's how to get around the bug:
If you're using ActiveAdmin, whichever table PG says doesn't exist, comment out the contents of that ActiveAdmin rb file.
For example, for this case PGError: ERROR: relation "users" does not exist, comment out the entire contents of app/admin/users.rb, then uncomment after you've done your migrations.
That issue for me was being caused by Factory Girl rails. I would recommend for those using it to rename the specs/factories folder to specs/temp and attempting
RAILS_ENV=your_environment bundle exec rake db:migrate --trace
If it passes, then you just found what was causing it. A quick dig through the Factory Girl Rails gem github repo helped me identify the issue.
The factories were failing because I was trying to instantiate a Model that didn't exist upon running! Code sample below:
FactoryGirl.define do
factory :billing_product, class: 'Billing::Product' do
name Faker::Cat.name
product_type 'fuel'
active true
payment_options [Billing::PaymentOption.new(term: 1, payment_term: 1)]
end
end
Encapsulating the Array in a block (adding {}) did the fix for me. Note that payment_options can take more than one payment option in the example...
payment_options {[Billing::PaymentOption.new(term: 1, payment_term: 1)]}
Refer to the Dynamic Attributes part of the Factory Girl Rails docs for more info.
Don't forget to rename your factories folder back!
I was facing the same problem and then I discovered the following solution.
Make sure You have entered all of the following credentials in the database.yml file and they are correct:
development:
adapter: postgresql
encoding: unicode
database: my_database
host: localhost
port: 5432
pool: 5
username: postgres
password: xyz
test:
adapter: postgresql
encoding: unicode
database: my_test_database
host: localhost
port: 5432
pool: 5
username: postgres
password: xyz
I had this problem after I deleted the users table. solutions was changing
change_table(:users)
to
create_table(:users)
::Migration[5.0] was missing in migrations.
instead of throwing syntax error it throws
PG::UndefinedTable: ERROR: relation roles does not exists
after wasting hours I finally figured out that migration is missing ::Migration[5.0].
Erroneous Migration:
class CreateRoles < ActiveRecord # <---- Pay attention
def change
create_table :roles do |t|
t.string :name
t.integer :code, limit: 2
t.boolean :is_active, default: true
t.timestamps
end
end
end
Fixed and Correct Migration
class CreateRoles < ActiveRecord::Migration[5.0]
def change
create_table :roles do |t|
t.string :name
t.integer :code, limit: 2
t.boolean :is_active, default: true
t.timestamps
end
end
end
This could be a bug with rails and might help someone, instead of struggling and wondering.
The most probable cause is that your rake is using different environment from database.yml than your webserver.
I was getting a similar error while trying to run tests using rspec.
I followed Малъ Скрылевъ's steps but still ended up short. The final step I needed to do was load my schema into my test database using:
RAILS_ENV=test rake db:schema:load
After that the problem went away and I could move on to the next bug. Hopefully that gives you some insight.
Remove the Admin folder and run rake again.
(I know this is old, but for future googlers)
Are you using devise? I know specifically omniauthable is a problem, but maybe others as well. It doesn't have to be devise though. Generically the solution is to comment out the offending model, class, whatever, and un-comment any sections the errors ask for.
For me, what was happening is that devise is reading the User model to see what you have as arguments for devise (the class method
i.e. devise :database_authenticatable, :registerable #etc)
But, it will read the whole file and if this isn't a new project it might get tripped up by other class methods relying on other things (in my case it was the friendly_id gem, and then an alias_method
The answer was to comment out the User model except for the devise lines(s) * and rake db:schema:load should run fine.
otherwise I got this error:
ArgumentError: Mapping omniauth_callbacks on a resource that is not omniauthable
Please add devise :omniauthable to the User model
If you get this error while migrating, make sure your model name is plural
e,g.
add_column :images, :url, :string
I had this problem and it turned out to be caused by Grape API. I noticed in the stack trace that the routes file was being read during the migration.
In routes.rb the Grape api is mounted
mount API::Base => '/'
And in the API were references to the missing model. So, thanks to this answer I put it in a block that detects whether its being run by the server or during the migration.
unless ( File.basename($0) == "rake" && ARGV.include?("db:migrate") )
mount API::Base => '/'
end
And it worked.
I was having the following error and doing a lookup into all my application code for type_zones I was unable to find it. I also looked at the db and it was updated.
Turns out it was a file under fixtures /test/fixtures/type_zones.yml that was causing the trouble.
ERROR["test_should_get_new", UsersControllerTest, 0.47265757399145514]
test_should_get_new#UsersControllerTest (0.47s)
ActiveRecord::StatementInvalid: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "type_zones" does not exist
LINE 1: DELETE FROM "type_zones"
^
: DELETE FROM "type_zones"
For anyone who is still having this problem, in my case, it was my factory in FactoryGirl that was triggering this error.
I was trying to add reference via '.new' or '.create'.
In my case, I had to comment out 2 ActiveAdmin files. Here were my steps:
Initial error/stacktrace (note we're using Solr on this project):
⇒ rkdbm
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
=> Solr is already running
rake aborted!
PG::UndefinedTable: ERROR: relation "discussions" does not exist
LINE 5: WHERE a.attrelid = '"discussions"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"discussions"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
/Users/matthewcampbell/Sites/code/stack-builders/AchieveX/app/admin/users.rb:25:in block in <top (required)>'
/Users/matthewcampbell/Sites/code/stack-builders/AchieveX/app/admin/users.rb:1:in'
/Users/matthewcampbell/Sites/code/stack-builders/AchieveX/config/routes.rb:3:in block in <top (required)>'
/Users/matthewcampbell/Sites/code/stack-builders/AchieveX/config/routes.rb:1:in'
/Users/matthewcampbell/Sites/code/stack-builders/AchieveX/config/environment.rb:5:in `'
Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)
I commented out the app/admin/discussions.rb file per Arcolye's answer above and tried to migrate my database again.
Same error.
I looked at the stacktrace a bit more closely, and noticed that in fact app/admin/users.rb:25 was throwing the exception - and sure enough, that file has a dependency on my discussions table (via executing Discussion.all).
Finally, commenting out the contents of users.rb allowed me to finally migrate my database successfully.
FYI: there's a discussion here in ActiveAdmin about whether that gem should load the database when required.
So having the same problem just now. Remember to have only one model in each migration. That solved it for me.
I came across the answer here.
I was catching the Error:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "users" does not exist
LINE 8: WHERE a.attrelid = '"users"'::regclass
It turned out to be a super easy fix. I had copied files over from an older version of the project and forgot to nest them inside of a "migrate" folder. When I did that it solved the problem for me.
it usually can happen when you use wrong type of association between models, check for dependency destroy and has_many associations, for example:
wrong way that can cause this trouble:
article.rb
has_many :subcategories, through: :categories, dependent: :destroy
subcategory.rb
has_and_belongs_to_many :articles
right way:
article.rb
has_many :subcategories, through: :categories, dependent: :destroy
subcategory.rb
declare association with categories here not articles (belongs_to / has_many_and_belongs_to)
Forgetting the migration file in your commit can cause this issue. When pushed on heroku for e.g. rails db:migrate will obviously not work. Be sure that the migration file defining the undefined table have been committed.
My case was also related to FactoryGirl/FactoryBot and I just had to change the definition. Replacing the constant by a string.
My env:
Rails 5.2.6
factory_bot 4.8.2
From this:
FactoryBot.define do
factory :user, class: Admin::User do
...
end
end
To this:
FactoryBot.define do
factory :user, class: 'Admin::User' do
...
end
end
Which is something recommended by Getting Started - Specifying the class explicitly.
I was trying to run test.rake script and encountered the same issue. Spent a lot of time trying to understand what's going on. Eventually, it get fixed after I renamed the file.
Related
I'm trying to deploy to heroku. First, I pushed to GIT and to heroku (using git push heroku). Then I wanted to migrate the db using heroku run rake db:migrate but after migration partially got the following error message:
-- add_foreign_key(:members, :organizations)
(16.5ms) ALTER TABLE "members" ADD CONSTRAINT "fk_rails_43c258b686"
FOREIGN KEY ("organization_id")
REFERENCES "organizations" ("id")
PG::DuplicateObject: ERROR: constraint "fk_rails_43c258b686" for relation "members" already exists
: ALTER TABLE "members" ADD CONSTRAINT "fk_rails_43c258b686"
FOREIGN KEY ("organization_id")
REFERENCES "organizations" ("id")
(1.2ms) ROLLBACK
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::DuplicateObject: ERROR: constraint "fk_rails_43c258b686" for relation "members" already exists
: ALTER TABLE "members" ADD CONSTRAINT "fk_rails_43c258b686"
FOREIGN KEY ("organization_id")
REFERENCES "organizations" ("id")
/app/vendor/bundle/ruby/2.1.0/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'
/app/vendor/bundle/ruby/2.1.0/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute'
/app/vendor/bundle/ruby/2.1.0/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:473:in `block in log'
...etc.
I have no data to loose, so tried heroku pg:reset DATABASE (also since I have tempered with existing migration files rather then everytime create a new one) and then heroku run rake db:migrate but with the same result.
In development, running rake db:migrate functions properly (I also used bundle exec rake db:reset to reset the development db). I don't seem to be experiencing problems in development, so it seems a Heroku problem. Does anyone have an idea what might be causing this?
Perhaps also relevant: I'm using the puma server of Heroku.
Update: One of the migration files contains:
1 def change
2 create_table :members do |t|
3 t.references :organization, index: true, foreign_key: true
4 t.string :email, null: false
5 etc
6 t.timestamps null: false
7 end
8 add_foreign_key :members, :organizations
9 add_index :members, [:organization_id, :username]
10 end
Are it perhaps lines 3 and 8 that are double? If so, what should I delete?
This simply indicates that there is already a foreign key from "members"."organization_id" to "organizations"."id". You might confirm whether that is so by examining the production database after the migration fails.
The foreign key must be getting created already by a previous migration, possibly when the members table is created. Are you using PostgreSQL in development? Maybe you're using a database that is less fussy about duplicate constraint definitions, or which does not create them under the circumstances that are creating the previous one on PostgreSQL in production.
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)
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.
I've come across a problem with running my migrations in a new rails app (3.2.3). We're using postrgres 9.1.3 and - pg (0.13.2) -
When I run rake db:create, then rake db:migrate, I get ->
1.9.3-p194 (master) rake db:migrate --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
PG::Error: ERROR: relation "roles" does not exist
LINE 4: WHERE a.attrelid = '"roles"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"roles"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
I get this even without any migrations defined, so I don't believe it's a problem with the migrations themselves. When I look at the stack trace, I see that scopes defined in my User model are being run - when I comment them out, the migrations run without a problem.
scope :team_leaders, where(role_id: Role.where(name: 'Team Leader').first.try(:id))
scope :area_leaders, where(role_id: Role.where(name: 'Area Leader').first.try(:id))
scope :nation_leaders, where(role_id: Role.where(name: 'Nation Leader').first.try(:id))
scope :employees, where(role_id: Role.where(name: 'Employee').first.try(:id))
Is this a bug in rails, or am I doing something wrong? I'd really appreciate some help - we can remove the use of these scopes across the app, but this is something we'd like to avoid.
Should I be putting these scopes inside some sort of conditional which is called when rails is loaded in the console or as a server but not during migrations?
Thanks very much,
Dan Sowter
I was having exactly the same problem. After 2 hours debugging and pulling my hair off, this blessed human being called Carl Zulauf posted the answer in the comments.
The problem is that the scopes are being evaluated when we run the migrations, so any dependency with another table that is not yet migrated will result in that error.
Just wrap all of your scopes with lambda. For instance:
scope :team_leaders, lambda { where(role_id: Role.where(name: 'Team Leader').first.try(:id)) }
Do that for all the scopes.
That should do the trick. They need to be lazy evaluated (just when get called), and without lambda they are being evaluated right away.
If your scopes begin with find_ like find_by_foo then they will break rake db:migrate.
That was the bug in my case.
I actually had same issue with migrations which caused by default scope, like this:
default_scope where(deleted: false)
Error was caused by such blocks of code:
ModelName.all.each_with_index do |m, i|
...
end
This problem solved via unscoping:
ModelName.unscoped.each_with_index do |m, i|
...
end
I am trying to push a simple app up to heroku and run:
heroku rake db:migrate
But I get the following error:
rake aborted!
PGError: ERROR: relation "posts" does not exist
: SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"posts"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)
My migration looks like this:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :source
t.string :tweetid
t.string :pure
t.string :media
t.string :destination
t.datetime :time
t.timestamps
end
end
end
And, after referring to another SO answer, I have included the following in my Gemfile:
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.1.4'
gem 'coffee-rails', '~> 3.1.1'
gem 'uglifier', '>= 1.0.3'
gem 'pg'
end
Thank you in advance for any help!
--- UPDATE ---
The main reason I am confused is that this all works locally, just not when I run the migration on heroku.
Here is the error I get now:
rake aborted!
Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.)
I have been looking at this question:
Heroku error when launch rails3.1 app missing postgres gem
I am almost-certain my database.yml should not look like this (seeing as I need to be running postgresql!!!):
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
Serious apologies for the nubishness here. Thank you for your help in advance!
Also tried this link: Uploading to Heroku DB rake:migrate problem
create_table :posts
Didn't you forget the s? The table names should be plural.
I just ran: bundle exec rake db:migrate and it worked
I had a similar problem, but it wasn't caused by the migration or the Gemfile. I had 4 models setup in a polymorphic relationship. Removing the statement
belongs_to :assetable, :polymorphic => true, :dependent => :destroy
and removing the subclass' acts_as_* declarations was enough to enable the db:migrate to successfully complete. I then added back the statements in the models and everything worked great. I'm not exactly sure why this is the case, but if you are in a similar situation this may help temporarily until a better solution presents itself.
My situation is polymorphic multi-table inheritance scheme between one parent and 3 objects using http://mediumexposure.com/multiple-table-inheritance-active-record/ as a baseline.
If you're using ActiveAdmin, whichever table PG says doesn't exist, comment out the contents of that ActiveAdmin rb file.
For example, for this case PGError: ERROR: relation "posts" does not exist, comment out the entire contents of app/admin/posts.rb, then uncomment after you've done your migrations.
Robin probably has it right but just in case...
Check the filename/timestamps on your migrations. These get run in sequence. I had an issue where a generator that made my migrations was putting the foreign table first...I switched the file names and it worked.
It's a long shot but I thought I'd put that out there.
In my case, I was doing rename_table in my migration, after having already modified my model name to reflect the new table name. I had moved User into User::User. The users table needed to be renamed to user_users, so my migration looked like
class RenameUsersTableWithPrefix < ActiveRecord::Migration
def up
rename_table :users, :user_users
end
def down
rename_table :user_users, :users
end
end
Instead of
app/models/user.rb
I now had
app/models/user.rb
app/models/user/user.rb
with the latter containing the User::User model, and the former containing simply
module User
def self.table_name_prefix
"user_"
end
end
It was this class method in the newly added User module that was giving me the PGError when running rake db:migrate like the OP had. Temporarily removing this class method while I ran my migration allowed the migration to run smoothly.
I was having the same problem. I ran heroku run rake db:migrate and that solved the problem.