Rails DB Migrate Error, Rails Re-running previous migration? - ruby-on-rails

I'm following the RailsTutorial.org tutorial, section 7.3 and trying to do a db migration using rake to add a password column to an existing database. What appears to be happening is that rails is re-running a previous migration file and trying to add table Users (which exists already) rather than the most recent migration file and add a password column. Any help would be appreciated!
Here is the code I ran to generate the migration file:
$ rails generate migration add_password_to_users encrypted_password:string
Then I ran rake db:migrate and got the following error:
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" varchar(255), "created_at" datetime, "updated_at" datetime)

Rails will run any migration whose number is not in the schema_migrations table in the relevant database. So, if it doesn't have the number for the migration to create the users table, it will run that migration, which will blow up as you have seen if the table happens to be there already.
I'm not familiar with the tutorial you're talking about - can you take me through what you have done already with your migrations?

It appears there was a problem with one of the other migration files -- I moved that file out of the migrate folder and re-ran rake and it worked.

Related

How to solve: SQLException: no such table: locations: ALTER TABLE "locations" ADD "user_id" integer

I'm having some DB issues with rails. When I run rails db:migrate I get the following error:
add_column(:locations, :user_id, :integer)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: no such table: locations: ALTER TABLE "locations" ADD "user_id" integer
The problem seems to be that I have a migration that is trying to add :user_id to a table :locations but this table does not exist because I deleted it and it is therefore not in the schema. How do I solve this? I always thought it was a bad idea to delete migrations.
It depends. Was locations created and deleted by migrations? If so, is the failing migration, in time terms, between those migrations?. If the answer is yes then you should not delete it.
In the other hand, if you deleted locations by hand or by migration before the failing migration then remove it, since it makes no sense to your schema.

Rails migration -- rake db:status says migration is down, but database is already migrated?

I have a local PSQL database setup and am having issues getting rake db:migrate to function properly. For instance, my database has already had its high_school column name changed to high_school_name, but rake db:migrate is failing, and the status reveals this:
up 20130307043554 Adding seo tables
up 20130307185401 Create admin notes
up 20130307185402 Move admin notes to comments
up 20130308160956 Add active flad to users
up 20130308214928 Add column public to users table
up 20130325203837 Add duration to videos
up 20130326171803 Update duration of videos
down 20130410145000 Fix high school name
up 20130410145028 Add high school id to users
up 20130410161705 Convert units for stats
up 20130410164209 ********** NO FILE **********
up 20130416142844 Add column coach id to users
Why is a migration in the middle of the migration order failing/being read as "down"? Here's the error:
Migrating to AddingSeoTables (20130307043554)
Migrating to CreateAdminNotes (20130307185401)
Migrating to MoveAdminNotesToComments (20130307185402)
Migrating to AddActiveFladToUsers (20130308160956)
Migrating to AddColumnPublicToUsersTable (20130308214928)
Migrating to AddDurationToVideos (20130325203837)
Migrating to UpdateDurationOfVideos (20130326171803)
Migrating to FixHighSchoolName (20130410145000)
(0.1ms) BEGIN
== FixHighSchoolName: migrating ==============================================
-- rename_column(:users, :high_school, :high_school_name)
(0.4ms) ALTER TABLE "users" RENAME COLUMN "high_school" TO "high_school_name"
PG::Error: ERROR: column "high_school" does not exist
: ALTER TABLE "users" RENAME COLUMN "high_school" TO "high_school_name"
(0.1ms) ROLLBACK
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::Error: ERROR: column "high_school" does not exist
: ALTER TABLE "users" RENAME COLUMN "high_school" TO "high_school_name"
Obviously, there is a schema issue or something. Schema is tracked via the remote branch though, so I don't know where the issue lies.
I suspect that the down was not able to handle the column rename change correctly, unless just adding or removing columns.
One option you may wish to consider is actually changing the name with SQL. For instance if a migration to change high_school to high_school_name is failing and the database itself currently has high_school_name, rename that (in SQL) to high_school and then try and run the migration. This may be one option for you.
Add resque nil to at the end of the row where column is renaming

Removing timestamp fields from the schema

I had used default generator to create some tables and they all had that t.timestamp in their definition so the schema that was created also has created_at and updated_at fields.
Now I am told that I don't need those two fields in my schema so I went to the original create_table* files and took out t.timestamp line from them and ran the db:migrate and schema:load commands
But still when I go to my schema.rb file I can see they are still there.
Is there anything wrong I am doing here?
Run
rails g migration remove_timestamps_from_table created_at updated_at
with table being your model's name. Since this is following the pattern remove x from y, rails is smart enough to generate the appropriate migration for you.
Then run
rake db:migrate
to update your development database and
rake db:test:prepare
to prepare the test database, and you're all set!
Read more on migrations here. If you are still having trouble, consider restarting your rails server or database server.

Rails DB Migration Error: relation already exists

I am getting an error when I try to migrate my db. I don't entirely remember how I got here, but I believe I:
created new branch, scaffolded 'Requests', db:migrated, switched back to master, and merged branch
created another branch, did some stuff, db:migrated, and everything was working fine.
pulled from heroku postgres database so i could test out if things worked with actual data. then tried db migrating, but gave me this error:
rake db:migrate
== CreateRequests: migrating =================================================
-- create_table(:requests)
NOTICE: CREATE TABLE will create implicit sequence "requests_id_seq1" for serial column "requests.id"
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::Error: ERROR: relation "requests" already exists
: CREATE TABLE "requests" ("id" serial primary key, "title" character varying(255), "content" text, "category" character varying(255), "status" character varying(255), "requested_track_id" integer, "created_at" timestamp, "updated_at" timestamp)
Any ideas?
I'm not sure exactly what pull strategy you used, but if we make two reasonable assumptions about your pull strategy:
it doesn't drop the database but just overwrites tables, since this requires less permissions.
it is operating in a sort of 'archive mode', meaning it doesn't drop tables on the destination just because they don't exist on the source. Think rsync; you have to specify --delete to get what might be your expected behavior with that utility.
If your steps are correct, then what happened is you overwrote the schema_migrations table, so Rails thinks you haven't added the table yet, but neither did your heroku pull drop the table because of #2 above.
Don't create another migration!!! This will fail on everyone elses' computer except yours, but will only run on yours once.
Instead, run rails dbconsole and execute something like DROP TABLE 'requests' (I forget the postgres syntax, might not be exactly that). Then you can run your migrations.
There is another way to avoid dropping a table with data in it.
What I do in those cases is to check which migration is failing.
Suppose you have a file db/migrate/20130908214222_create_requests.rb, and for some reason, ActiveRecord failed in the past when stored this migration in its "tracking system".
To be sure that this is the case, just find, in the schema_migrations table, a row containing a number like this example: 20130908214222
If that row does not exist, you just have to insert a new one:
INSERT INTO schema_migrations(
version
) VALUES (
20130908214222
);
Next time you run rake db:migrate, ActiveRecord will omit this step, and will continue migrating to end without complications.

Marking Rails migrations as migrated

I've ended up with 9 migrations effectively duplicated. (I think this is because I installed/updated Gems and/or pulled in their migrations on both my dev and production machines, but am not entirely sure at this stage.)
I moved out one set of the duplicated 9 from the rails directories on the production server, but now that I want to db:migrate on production in order to run another migration, I'm getting:
$ bundle exec rake db:migrate RAILS_ENV=production
[DEPRECATION WARNING] Nested I18n namespace lookup under "activerecord.attributes.checkout" is no longer supported
== CreatePages: migrating ====================================================
-- create_table(:pages)
rake aborted!
An error has occurred, all later migrations canceled:
Mysql2::Error: Table 'pages' already exists: CREATE TABLE `pages` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `title` varchar(255), `body` text, `slug` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB
This is because the migrations have effectively already been run.
I'd rather avoid doing db:migrate:down and db:migrate:up for each one - I think this will mean data in the production database is lost. (A couple of static pages in Spree in this case.)
Is there a way I can tell this installation of Rails to forget all outstanding migrations, effectively marking all outstanding migrations as done?
I solved it like this:
Go to the conflicting migration file.
Erase the content and save it.
Run rake db:migrate
Ctrl+Z the file to the previous state.
This was an special case, because I had copied the DB from another app, and I had conflicting migrations, and stuff.
You can add the timestamps of the migrations to the schema_migrations table. However why is that table missing from the database or missing the rows it needs?
It is likely to be the case that this particular migration has got half way through and failed, thus when you are trying to run it again the first part of the migration will not work as it has been done previously. This is a limitation of MySQL as it can't rollback migration changes that fail part of the way through. Postgres on the other hand can rollback structural changes to the database thus avoiding this issue.
By default rake db:migrate runs all the pending migrations. So, in order to get your migrations right.. for the sake ..comment out those migrations and afterwards revert those back to normal. It will ensure that you are ok in future migrations.
You can also, in a Rails console, use the ActiveRecord::SchemaMigration model to add the timestamps into the schema_migrations table.
ActiveRecord::SchemaMigration.create! version: '20210724133241'

Resources