Similar questions has been asked a lot. But, I think my situation is a bit different. I pulled a db from Heroku (I use sqlite3 in prod) to my local machine (uses PostgreSQL ). The prod db didn't have any data at that time.
After that time I haven't done any db migrations to test. Now I have a couple of fields in my dev db. However, when I go to test console to see what I have (referring a User table) User.count returns 0, but returns 2 users in dev.
So I did rake db:migrate RAILS_ENV=test there was neither an error message nor a success message. I thought it was success and checked the test db if it has those 2 users and still nothing. Then I tried bundle exec rake db:test:prepare. This was the output
**You have 4 pending migrations:
20120415210441 CreateUsers
20120418064930 AddIndexToUsersEmail
20120419034627 AddPasswordDigestToUsers
20120504031144 AddRememberTokenToUsers
Run `rake db:migrate` to update your database then try again.**
What is the solution?
EDIT:
FYI: I am using windows
I also run rake db:migrate and I got this error.
$ rake db:migrate
== CreateUsers: migrating ====================================================
-- create_table(:users)
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "users" already exists: CREATE TABLE "users" ("id"
INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "email" varcha
(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
The error message indicates that your dev and test migrations are out of sync.
First run migrate on dev. This will update dev with all your recent migrations.
rake db:migrate
Then run db:test:prepare. This will make the test database the same schema as dev.
rake db:test:prepare
Now, understand that db:test:prepare makes test have the same schema as dev, but with no records. To populate records in test, implement fixtures or factories (see the factory-girl gem). Factories are generally called in your test to create records for that test.
That's another question and another answer.
You should drop the table and re-run the migrations.
If you don't know how to drop a table in SQLite, then
comment out the create_table method call in the 20120415210441_CreateUsers.rb.
Run > rake db:migrate VERSION=20120415210441
Run > rake db:migrate VERSION=??? where ??? is the version of the migration prior to CreateUsers.
Uncomment the code in 20120415210441_CreateUsers.rb
Run > rake db:migrate
Related
I have the current migration
class CreateSlugSequence < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
CREATE SEQUENCE slug_sequence
SQL
end
def down
execute <<-SQL
DROP SEQUENCE slug_sequence
SQL
end
end
I run rails db:migrate
Enter rails c (development mode)
Run ActiveRecord::Base.connection.exec_query("select nextval('slug_sequence')")[0]['nextval']
And get the expected value
But if I enter rails c in test mode, for some reason, the sequence table does not exist
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "slug_sequence" does not exist
I ran ActiveRecord::Migrator.current_version, to check what was the last migration applied and it returns the latest version.
Thanks for the help in advance.
I recommended dropping the test db and recreating it. Although these should remain in sync they sometimes do not and you have to do manual steps to get them together.
RAILS_ENV=test rake db:reset
Weird that it is not working with that, would be interesting to drop a pry debugger in that task and see what is going on. https://github.com/rails/rails/blob/master/activerecord/lib/active_record/railties/databases.rake#L122
Manual steps
RAILS_ENV=test rake db:drop
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:migrate
I found the way to fix rails db:reset command, you just need to add line config.active_record.schema_format = :sql in your application.rb so info about sequence will be stored in structure.sql. Please take a look that with default schema dump :ruby info about seqeunce is not stored in schema.rb file.
Important: make sure to firstly create structure.sql with rails db:migrate and then run rails db:reset. After just rails db:migrate I'm still getting the error you want to fix.
First I ran: rails generate model User name:string email:string and this create a migration. Later I did a db:migrate and I get this error:
bundle exec rake db:migrate
== 20150728195629 CreateUsers: migrating ======================================
-- create_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "users" already exists.....
When you generate model the table user is created but then when you rake db:migrate it tries to create it again.
I'm confused! Am I doing something wrong?
https://www.railstutorial.org/book/modeling_users#code-generate_user_model
just run into the console
rails console
and type in
ActiveRecord::Migration.drop_table(:users)
and then
exit the console and
rake db:migrate
You must have created a table as Marsatomic said. Run
bundle exec rake db:migrate:status
And look at your migration history to see where you created it. If you see it, you can roll back your migrations past that table, delete the migration file that created it, and then re-run your migrations. If you don't see it anywhere, you must have created the table without a migration. At that point you should do as Marsatomic instructed in his comment above.
you can use 'db:reset', it == 'db:drop db:create db:migrate'
just run into the console
rails db:reset
just run into the console
bundle exec rails db:migrate
I am trying to run the command on Heroku
Heroku run rake db:migrate
but I get the error:
Migrating to AddNameToUsers (20130320002032)
== AddNameToUsers: migrating =================================================
-- add_column(:users, :name, :string)
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::Error: ERROR: relation "users" does not exist
: ALTER TABLE "users" ADD COLUMN "name" character varying(255)
This might have to do with the fact that I had some issues with the migration files on my local server. I managed to work around it and had to delete one of the files, but I worry that I might have deleted something I need that hadn't been migrated to heroku's database?
my github for the account is https://github.com/jeremybelcher/omrails
Any help is appreciated
Your previous migrations are missing.
You can do:
rake db:create
rake db:schema:load
rake db:migrate
Which will recreate your database based on your schema.rb file.
I'm finishing a major refactoring of an app and I am trying to clean up the migrations. I've made the changes and everything works great locally after reseting and re-migrating the database.
On production I can't get the migrations to run. I've tried every combination of reset, drop, etc. that I can think of but I keep getting this error.
It seems like the production database isn't being reset which is causing the migration to break. Any tips would be appreciated.
== AddFieldsToUsers: migrating ===============================================
-- add_column(:users, :company, :string)
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: duplicate column name: company: ALTER TABLE "users" ADD "company" varchar(255)
For resetting the database you can drop and migrate the database again in production mode.
rake db:drop db:create db:migrate RAILS_ENV=production
And, if you want to edit some particular migration, you can reset it using its version no.
rake db:migrate:down VERSION=<version no.> RAILS_ENV=production
Edit the migration file, and then
rake db:migrate:up VERSION=<version no.> RAILS_ENV=production
I'm working through the rails tutorial and have gotten stuck. Starting at Listing 8.16 I have made the following modifications to <timestamp>_add_remember_token_to_users.rb:
class AddRememberTokenToUsers < ActiveRecord::Migration
def change
add_column :users, :remember_token, :string
add_index :users, :remember_token
end
end
The guide then says to update dev & test db as usual:
$ bundle exec rake db:migrate
$ bundle exec rake db:test:prepare
My User test for the *remember_token* is still failing so I took a look at the user table in dev and tests database with command line sqlite3. They look like this:
sqlite> .schema users
CREATE TABLE "users" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"name" varchar(255),
"email" varchar(255),
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL,
"password_digest" varchar(255));
CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email");
It seems like my migration has not been run yet but I do not know how to force it to run.
Try to rebuild your database structure(WARNING: all db-data will be lost):
rake db:drop:all
rake db:create:all
rake db:migrate
If you use Rails < 4.1, don't forget to prepare test database:
rake db:test:prepare
This is the easiest solution since you are working with tutorial. However in production or having important data in development you should take time to investigate the issue. In this case you most likely had created an empty migration, ran rake db:migrate, then added instructions to the migration, so you don't see a new field and further rake db:migrate does nothing. To resolve this issue you need to comment your change instructions, perform rake db:rollback, uncomment instructions and then rake db:migrate to apply instructions you missed.
I had the same issue as the initial question. $ bundle exec rake db:migrate wasn't adding remember_token to the .db and Latha Doddikadi's answer worked for me.
I did:
rake db:rollback
and then:
$ bundle exec rake db:migrate
which added the remember_token field to the database followed by:
bundle exec rspec spec/models/user_spec.rb
which passed.
Finished in 0.92841 seconds
21 examples, 0 failures
Roll back and then re run the migration it might work.
rake db:rollback
And after rolling back re run your migrations again.
I had a bizarre case of the last migration simply refusing to run. I'd created the migration file manually. So I deleted it and remade the migration using
rails g migration ...
and copied the code into the new file and it ran.
I didn't discover why manually creating that file didn't work; all I know is doing it the 'right/rails way' fixed the issue.
Leaving this here in case it helps someone else.