Remove a column which was added recently - ruby-on-rails

There was a time when I had to a column "column" to a model. Now I have to remove it. Is there any sensible method to that except a simple one by adding a new migration?

Depending on how deep down the rabbit hole you are you can rollback then delete the migration.
rake db:rollback
rails destroy migration *name of migration*
This will run the down method of the migration undoing the column add. The second command destroys the migration resetting your schema file.
EDIT:
Turns out your rabbit hole is deep. Best thing to do is to make another migration removing the column.

You can of course run SQL directly on the database. The problem with not using a migration file to perform this "subtle change" is that if you ever have to move your application to another server, you won't be able to recreate the database: this "column" column will be there because it's removal was never documented.
Stick with migrations!

Related

Can I delete an empty EF Migration safely

I've just reviewed a colleague's work and there is an empty EF migration in his PR (up and down methods contain no code). There is another migration after this with DB modifications.
I believe that this empty migration can be deleted on the basis that it does absolutely nothing. There should be a corresponding entry in the _MigrationHistory table, which can also be deleted safely, in my opinion.
My colleagues believe that it should be left in there "just in case".
Are there any EF experts who can say which approach is best, and why?
Тhe truth is somewhere in the middle. You can delete it, but do not delete the migration file directly.
-> Removing A Migration
The following command removes a migration:
[Command Line]
dotnet ef migrations remove
[Package Manager Console]
remove-migration
You will use this command to remove the latest migration. This will remove the class file that was generated for the latest migration and it will also revert the ModelSnapshot file back to the state of the previous migration. If there are no pending migrations, an exception will be raised. If you want to remove a migration that has been committed, you must reverse the migration first (see below).
You should always use commands to remove a migration instead of simply deleting the migration code file, otherwise the snapshot and migrations will fall out of sync with eachother. Then future migrations will be based on a model that is incorrect. Nevertheless, the remove command will recognise if migration files have been deleted and will revert the snapshot accordingly.
If you need to remove a migration that was generated before the most recent one, you must remove all sunsequent migrations first, then adjust the model and then create a new migration to cater for the changes.
Sores: https://www.learnentityframeworkcore.com/migrations

deleting migration, any problems?

I generated a migration, add_content_to_users content:string. I ran db:migrate and in the edit page I added text into this content attribute. I realized I wanted to do something else, so I want to get rid of content. Is db:rollback sufficient, or do I have to also reset and migrate the database again (would rather not) using something like db:migrate:reset?
rake db:rollback undoes the last migration (in most cases) if it added a column, it will drop said column completely from your database table. All data in the column is lost.
If you don't alter or remove that migration file of course, the column will be added again the next time you run rake db:migrate.

Reorder/change timestamp on migration files

One of my migration files is referencing another table/model that will will be created further down the migration sequence.
Postgres doesn't like that:
PG::UndefinedTable: ERROR: relation "users" does not exist
So I wonder if there are any potential problems to manually reorder the migration files (by inventing new timestamps/prefixes)?
The affected tables are already down migrated.
When you run rake db:migrate command it compares schema_migrations table and migration files located in db/migrate folder. All the migrations which were not executed receive MigrationClass#up call then.
So starting from the point when your code is already published and/or migrations are run by other users, changing your migrations timestamps/names may lead to unprocessable migration procedure (as schema_migrations will treat a migration with changed timestamp as new, unprocessed one, and try to process it "again"). Possible workaround for this would be to comment the contents of up method for a while and uncomment it back after migrations are done. For fun you can also manipulate schema_migrations table directly from your db console (adding or removing necessary records). Both of these ways smells like a hack though.
Until then... Everything should work flawlessly.
This is what worked for me for this same situation, even though it's a hack.
Rails runs migrations in order of the timestamp, and Rails tracks which migrations have been run by the timestamp part of the migration file name, but not by the rest of the file name. So if you need to change the order of two migrations because the earlier one references the later one you can simply switch the 14 digit timestamp portion of the filenames by renaming both migration files. If the timestamp is off by even one digit Rails will think it's a new migration so write them down before changing them.

How to keep overview of the migrations?

I have a question regarding my migrations in rails.
Normally when i want to add a colum to a model for i dont make extra migrations but instead i perform this steps:
rake db:rollback
next i change the migration file in db/migrations and rerune:
rake db:migrate
The biggest problem is that when i do this i loose my data.
Previous i wrote migrations from the command line with for example
rake g migration Add_Column_House_to_Users house:string
The problem with this approach is that my db/migrations folder afterwards get very large and not very clear! I mean at the end i dont know wich variables the object has! Im not an expert in rails and would like to ask you how to keep the overview over the migrations!Thanks
Just a minor thought - I just use the file db/migrate/schema.rb to determine whats in the database as opposed to tracking through the migrations
You definitely shouldn't use db:rollback with a table with existing data.
I have a few production RonR apps with a ton of data and there are 100+ entries in the migrations table and adding new migrations to tweak tables is the rails way to do things. Not sure what you mean by lucid, but your schema and data model are going to change over time and that is ok and expected.
One tip. The migrations are great, but they are just the beginning, you can include complex logic as needed to fix your existing data (like so)
Changing data in existing table:
def up
add_column :rsvps, :column_name_id, :integer
update_data
end
def update_data
rsvps = Rsvp.where("other_column is not null")
rsvps.each do |rsvp|
invite = Blah.find(rsvp.example_id)
...
rsvp.save
end
end
Another tip: backup your production database often (should do this anyway), but use it to test all of your migrations before deploying. I run scripts like this all the time for local testing:
mysql -u root -ppassword
drop database mydatabase_dev;
create database mydatabase_dev;
use mydatabase_dev;
source /var/www/bak/mydatabase_backup_2013-10-04-16.28.06.sql
exit
rake db:migrate

db:migrate has no effect

If I edit my shema, and run db:migrate the database doesn't changed, but if I clear to version 0, and recall migration it's works, but I lost all database data.
What's wrong?
That's how db:migrate works. It maintains a table in the database called schema_migrations that keeps track of the migration timestamps (i.e. if your file is called 20090807152224_create_widgets.rb, the 20090807152224 part is the timestamp -- and the line that will get added to your schema_migrations table).
You're not supposed to modify the schema.rb file by hand -- that file gets autogenerated as a result of db:migrate.
The thinking in rails is that if you want to make a change to your schema, you're going to generate a new migration with those changes and then run db:migrate (which, as a result, will update the schema.rb file appropriately).
When you say you are updating your schema, does that mean you're updating the db/schema.rb file, or actual migrations?
If you're updating the schema.rb file, you should note that it will have no effect because the file is auto-generated.
See the comment at the top of the file:
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
It sounds like you were changing a migration file.
Don't change migration files. Add new ones. You can have migrations that change say, the type of a column. There are times when changing old migrations may be helpful, but don't do it unless you know the consequences. As others have mentioned, don't change the schema either, but I don't think you were doing that.

Resources