I'm following along with the rails tutorial. I'm on ch. 6 and I'm getting a strange error with SQLite3 (for the record, I'm using sqlite version 1.3.10 and the tutorial uses 1.3.9)
I don't get an error when I run rake db:migrate, but when I run the migration for the test environment, here's what I get:
$ bundle exec rake test:models
rake aborted!
ActiveRecord::PendingMigrationError:
Migrations are pending. To resolve this issue, run:
bin/rake db:migrate RAILS_ENV=test
sample_app/test/test_helper.rb:3:in `<top (required)>'
sample_app/test/models/user_test.rb:1:in `require'
sample_app/test/models/user_test.rb:1:in `<top (required)>'
Tasks: TOP => test:models
(See full trace by running task with --trace)
$ bundle exec rake db:migrate RAILS_ENV=test
== 20150628011937 AddIndexToUsersEmail: migrating ===========================
==
-- add_index(:users, :email, {:unique=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::ConstraintException: UNIQUE constraint failed: users.email: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constrain
t failed: users.email: CREATE UNIQUE INDEX "index_users_on_email" ON "users"
("email")
sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
SQLite3::ConstraintException: UNIQUE constraint failed: users.email
sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Here is my user.rb model:
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
Here is my most recent migration
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
end
end
I can post any other files if those are relevant. Thanks in advance for the help!
The problem was that I had users in the database with the same email before the migration.
db:reset solved everything
I experienced it for a bit different reason and here is the solution.
For me the error was
Minitest::UnexpectedError: ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2018-05-09 18:23:59.827561', '2018-05-09 18:23:59.827561', 298486374)
Notice the INTO "users" ("created_at", "updated_at", "id"). It was caused by test/fixtures/users.yml was not filled, so then there was duplicate values in columns which has unique key constraint.
test/fixtures/users.yml:
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
if you can't reset:db you should try to delete it by hand go to db folder and delete the "development.sqlite3" and the "test.sqlite3" files
then run
rails db:migrate
and bin/rails db:migrate RAILS_ENV=TEST
worked for me, anyway...
If this happens to you when running tests:
Make sure there are no users fixtures, unless you explicitly define those users with unique attributes.
test/fixtures/users.yml
When you generate a model, for example:
rails g model User
Rails automatically creates that file and it looks like:
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
This can mess up your tests.
Just use rake db:test:prepare and it will copy the dev database to test so you don't need to run the migrations.
I had to delete my development.db to resolve the issue.
Related
I am having trouble running any rake task for my Rails application, and no matter what task I run (rake db:migrate, rake db:reset, etc), I get the following error:
rake aborted!
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: pages: SELECT "pages".* FROM "pages"
I continue getting this error - no matter what rake task I run, and also when I try to run the server:
rails s
gets the following error
Exiting
/Users/terencedevine/.rvm/gems/ruby-2.1.2/gems/sqlite3-1.3.11/lib/sqlite3/database.rb:91:in `initialize': SQLite3::SQLException: no such table: pages: SELECT "pages".* FROM "pages" (ActiveRecord::StatementInvalid)
Everything I find online suggests using rake db:reset but that returns the same error.
One of my more recent migrations I ran was a XXXX_create_pages.rb which has the following code:
class CreatePages < ActiveRecord::Migration
def change
create_table :pages do |t|
t.string :name, null: false, unique: true
t.string :title, null: false
t.text :body
t.timestamps null: false
end
end
end
Any help is greatly appreciated! Thanks!
UPDATE
You need to make sure you actually execute your migrations.
Try rake db:migrate then try to run your server or console again.
Make sure to run rake db:create and then rake db:migrate and that should work.
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: pages: SELECT "pages".* FROM "pages"
From the error message, it's obvious that the pages table does not exist in your database right now. It got deleted somehow even if you did not delete it knowingly.
So, you should create the pages table again by running the corresponding migration:
rake db:migrate
In case your schema version exceeded to migration XXXX_create_pages.rb then rename you migration with greatest timestamp.
Eg.
Your page migration is
20151130203912_create_pages.rb
If your current schema version is
ActiveRecord::Schema.define(:version => 20151211175046)
Then pages migration must be 20151230203912_create_pages.rb
I hope it would be helpful.
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.
I'm new to Ruby on Rails and I'm following the https://www.railstutorial.org/book/ guide to understand a bit more about it. I'm stuck at 6.3.3, where it tells to create a secure password. The previous migration seemed to have worked (to create a unique index and to create the secure password column). After that when i try to run:
rake test
it says that the test was aborted and that i should run:
rake db:migrate RAILS_ENV=test
but when i do run the command above it returns this:
c:\Sites\sample_app>rake db:migrate RAILS_ENV=test
DL is deprecated, please use Fiddle
== 20141226095217 AddIndexToUsersEmail: migrating =============================
-- add_index(:users, :email, {:unique=>true}) rake aborted! StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::ConstraintException: indexed columns are not unique: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")c:/Si tes/sample_app/db/migrate/20141226095217_add_index_to_users_email.rb:3:in `change' C:in `migrate' Tasks: TOP => db:migrate (See full trace by running task with --trace)
I don't understand why this is happening. My DB is empty.
As requested, the migrations files:
20141226095217_add_index_to_users_email.rb
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
end
end
20141226095746_add_password_digest_to_users.rb
class AddPasswordDigestToUsers < ActiveRecord::Migration
def change
add_column :users, :password_digest, :string
end
end
See https://stackoverflow.com/a/14765346/429758 for the exact same issue. As mentioned there, the issue is not with the migration, but with having duplicate values for email field in the users table.
Since this error is happening while running tests, it means the test database has duplicate emails for users.
Rails Tutorial book uses fixtures to setup test data. The test/fixtures/users.yml file used to create the users on test env is shown in Listing 6.29 as follows:
one:
name: MyString
email: MyString
two:
name: MyString
email: MyString
Both of these fixtures having MyString as email is what is causing the migration to fail. Change the values to make sure both have different values.
Example:
one:
name: First User
email: first#example.com
two:
name: Second User
email: second#example.com
EDIT
Looking back at the Rails Tutorial, the next step in Listing 6.30 is to empty the test/fixtures/users.yml file. That is another way to ensure this error does not occur.
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.