I'm currently following the ruby on rails tutorial: http://guides.rubyonrails.org/getting_started.html.
I am trying to save data into the database. However, when I run: rails server I get the following error:
Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development
I've looked at the other articles and when I run:
bin/rake db:migrate
I get a rake aborted!
After running:
rake db:abort_if_pending_migrations....
I see that:
You have 1 pending migration:
20150805200129 CreateDatabases
SQLite3::SQLException: table "databases" already exists:
and it just tells me to run rake db:migrate to start again.
It seems that it already exists. Is there a way to cancel the pending migration?
Sometimes, even dropping a local development database is not a good idea.
There are better ways to delete/destroy a specific migration in your Rails application.
You could use rails d migration command to destroy a particular migration:
rails d migration MigrationName
To undo the changes corresponding to a particular migration, you can use db:migrate:down method like this:
rake db:migrate:down VERSION=XXX
Sometimes, things could get more messy and in those situation another handy thing is to take a look at the schema_migrations table in your database which has all the migrations with their version saved in it.
You can delete a particular migration from this table like this:
delete from schema_migrations WHERE version = VERSION;
if you don't want that migration to be present anymore.
Your migration may have failed midway (so it created the table, but didn't finish).
You are just using development environment, so it's okay to just drop the database and rebuild it from scratch:
rake db:drop # THIS WILL DELETE YOUR DATABASE
rake db:create
rake db:migrate
If you are like me and maintain your database structure outside of Rails, you can just delete the migration file from db/migration. I got the error in the OP's question when I used the rails generate command to create a model class, forgetting that it also creates a migration file.
Do not use this method if you rely on Rails to maintain your database structure!
I keep my Rails structure file up to date by building it from the database using:
bundle exec rake db:structure:dump
I do not encourage to drop the database and start from the beginning especially when you already have the data inside the database.
My approach to this will be migrate first, then rollback. After that you can safely delete the migration file. So the procedure is as following.
rails db:migrate
rails db rollback
rm db/migrate/your_last_migration_file.rb
You can recreate database and run all migrations in your development environment with such command
rails db:migrate:reset
If you want to revert the wrong migrations, You can drop the whole db using this:
rake db:drop
Then remove the migrations file manually(This wont corrupt the db when you recreate as the Schema migrations would be dropped as well).
Then run
rake db:migrate
And if there is data to be seeded, then run this as well
rake db:setup
I've run rake db:migrate and all of my migrations ran. However, when I try to run rake db:test:prepare I get the error:
You have 1 pending migrations:
20130724211328 CreateGalleries
Run `rake db:migrate` to update your database then try again.
Then running rake db:migrate again gives the error:
PG::Error: ERROR: relation "galleries" already exists...
But in the console I can create and manipulate the Gallery model exactly as shown in the CreateGalleries migration. The table is not being created or even mentioned in any other migrations.
It seems the migration ran just fine but did not register. Any ideas how to fix this?
EDIT
I solved this with rake db:drop db:create db:migrate then rake db:test:prepare, but I'm happy to give the solution to anyone who can shed light on what caused the problem in the first place.
I suspect the migration for galleries hasn't been executed properly. If you're 100% sure everything is right in your table, you can bump up the migration version to the version of the galleries migration.
To do this, find the timestamp of your galleries migration (the 14 numbers in front of your migration file, in this case 20130724211328) and insert this as a new row into the table schema_migrations (which is done automatically by Rails after successfully executing a migration).
If the table is empty, you could also drop the table galleries and run rake db:migrate again. This way you can also make sure your migration doesn't trigger any errors.
I am very new in ruby-on-rails. I have doubt in rake. create function is create a new db. After that, we want to run some commands like
rake db:load
rake db:data:load
rake db:schema:load
rake db:migrate
rake db:seed
But why we want to run this cmds after create the db and what function of the about cmd.
Thanks for your advice.
You can use rake -T to get the description of each task:
$ rake -T | grep db
rake db:create # Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)
rake db:drop # Drops the database for the current Rails.env (use db:drop:all to drop all databases)
rake db:fixtures:load # Load fixtures into the current environment's database.
rake db:migrate # Migrate the database (options: VERSION=x, VERBOSE=false).
rake db:migrate:status # Display status of migrations
rake db:rollback # Rolls the schema back to the previous version (specify steps w/ STEP=n).
rake db:schema:dump # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load # Load a schema.rb file into the database
rake db:seed # Load the seed data from db/seeds.rb
rake db:setup # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)
rake db:structure:dump # Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql
rake db:version # Retrieves the current schema version number
I this what you were asking about?
EDIT:
You can read more about what migrations are for here: http://guides.rubyonrails.org/migrations.html
EDIT 2:
rake db:migrate allows you to update the DB schema in a "sane" way: you can create a new migration (read the guides!) and add a new column for example, add an index, rename a column, etc. - migrations allow you to "travel" back and forth in "time" - you can run the migration and rollback it later.
When you generate a new migration:
$ rails g migration add_new_column_to_some_table you will be able to run rake db:migrate later on to apply to changes you want (of course you have to write the body of this generated migration).
I STRONLY advise you to read the guides though :)
EDIT 3:
add_column :users, :price, :float, for example, will add price column to the users table, the type of the column will be float (float isn't a best idea to store money related things BTW!). This column will be NULL by default.
EDIT 4:
Information about which migrations were run is stored in schema_migrations table: running migration for the first time will add a new record in this table with version of this migration (date + some random numbers from the name of the file). Rollbacking a migration will remove this record. Running a migration twice will not have any effect.
Simply put, db:migrate doesn't destroy existing data you have in your database. so running migrations and that rake task allows your data to exist from changes you make.
Workflow in words
You create an empty data base.
You will want to add a table of data for your first model into the database. This is done by editing a file in db/migrate
Now you want a second model, so you create your model and edit the migration file in db/migrate that was created for you
The easiest way to update your database without destroy any of the existing data, is to run bundle exec rake db:migrate. This adds the contents of the second migration file into the db and won't hurt existing data.
Example workflow after creating a project:
bundle exec rake db:create:all
bundle exec rails generate scaffold Users name:string email:string
bundle exec rake db:migrate
At this stage, bundle exec rails s and go to localhost:3000/users/new and create a new user.
bundle exec rails generate scaffold Posts title:string body:text
bundle exec rake db:migrate
Back in your browser go to localhost:3000/users and you should still see the user you created.
I'm writing my first Rails app. I've run a few rails generate model ... and rake db:migrate commands, but I now want to change my data model and so need to undo a few migrations.
The docs say I can undo a migration with rake db:rollback, but this isn't working. When I run this in the console the computer thinks for a few seconds but doesn't make any changes to db/migrate/ or db/migrate/schema.rb. No output is printed to the console.
Is this behavior correct? Shouldn't db:rollback be changing my schema? If so, can anyone think why it might not be working?
I'm on Rails v. 3.2.6.
EDIT
At the moment rake db:migrate:status gives
database: db/development.sqlite3
Status Migration ID Migration Name
--------------------------------------------------
up 20120617191211 Create irs
up 20120701154357 Create paths
up 20120701154421 Create nodes
up 20120702151447 ********** NO FILE **********
down 20120702155140 Create venues
down 20120703233833 Remove path from venues
Solution (see my comment): run
rake db:migrate:status
and correct problems you find there. In this case (per #MarkThomas' followup), you might want to check all files you need are in place.
This is what worked for me. Combine the steps given in this answer and comment by dB.
run rake db:migrate:status
If you have a ****NO FILE**** entry, just note the version number as noFileVersion. Note the version of the entry just above no file entry(stable_version).
created a "dummy" file with name noFileVersion_create_nothing.rb, and body
class CreateNothing < ActiveRecord::Migration[6.0]
def change
end
end
run rake db:migrate VERSION=stable_version
remove the noFileVersion_create_nothing.rb manually.
run rake db:migrate.
run rake db:migrate:status again to check if No file entry has disappeared.
The following worked for me:
rake db:migrate:down VERSION=20190304092208
Version number can be obtained by the following command:
rake db:migrate:status
This was the last version number to rollback one last migration
NOTE: Use the suggestions with caution, it is very dangerous for non-dev environments.
If
rake db:migrate:status
gives you a migration that says
up 20120702151447 ********** NO FILE **********
Then the best thing to do would be to do a (note that the following command will drop the database):
rake db:reset
to redo all migrations. If the last migration is the one missing, then schema.rb will have the last migration that rake db:migrate will look for:
ActiveRecord::Schema.define(:version => 20120702151447) do
Change that number to the last one in your migrate folder.
I have the migration file db\migrate\20100905201547_create_blocks.rb.
How can I specifically rollback that migration file?
rake db:rollback STEP=1
Is a way to do this, if the migration you want to rollback is the last one applied. You can substitute 1 for however many migrations you want to go back.
For example:
rake db:rollback STEP=5
Will also rollback all the migration that happened later (4, 3, 2 and also 1).
To roll back all migrations back to (and including) a target migration, use: (This corrected command was added after all the comments pointing out the error in the original post)
rake db:migrate VERSION=20100905201547
In order to rollback only one specific migration (out of order) use:
rake db:migrate:down VERSION=20100905201547
Note that this will NOT rollback any interceding migrations -- only the one listed. If that is not what you intended, you can safely run rake db:migrate and it will re-run only that one, skipping any others that were not previously rolled back.
And if you ever want to migrate a single migration out of order, there is also its inverse db:migrate:up:
rake db:migrate:up VERSION=20100905201547
rake db:migrate:down VERSION=20100905201547
will roll back the specific file.
To find the version of all migrations, you can use this command:
rake db:migrate:status
Or, simply the prefix of the migration's file name is the version you need to rollback.
See the Ruby on Rails guide entry on migrations.
To rollback the last migration you can do:
rake db:rollback
If you want to rollback a specific migration with a version, you should do:
rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION
For example, if the version is 20141201122027, you will do
rake db:migrate:down VERSION=20141201122027
to rollback that specific migration.
You can rollback your migration by using rake db:rollback with different options. The syntax will be different according to your requirements.
If you want to rollback just the last migration, then you can use either
rake db:rollback
or
rake db:rollback STEP=1
If you want rollback number of migrations at once, then you simply pass an argument:
rake db:rollback STEP=n
where n is number of migrations to rollback, counting from latest migration.
If you want to rollback to a specific migration, then you should pass the version of the migration in the following:
rake db:migrate:down VERSION=xxxxx
where xxxxx is the version number of the migration.
Use:
rake db:migrate:down VERSION=your_migrations's_version_number_here
The version is the numerical prefix on the migration's file name.
How to find the version:
Your migration files are stored in your rails_root/db/migrate directory. Find the appropriate file up to which you want to rollback and copy the prefix number.
For example:
File name: 20140208031131_create_roles.rb
Then the version is 20140208031131.
Rolling back the last migration:
# rails < 5.0
rake db:rollback
# rails >= 5.0
rake db:rollback
# or
rails db:rollback
Rolling back the last n number of migrations
# rails < 5.0
rake db:rollback STEP=2
# rails >= 5.0
rake db:rollback STEP=2
# or
rails db:rollback STEP=2
Rolling back a specific migration
# rails < 5.0
rake db:migrate:down VERSION=20100905201547
# rails >= 5.0
rake db:migrate:down VERSION=20100905201547
# or
rails db:migrate:down VERSION=20100905201547
To rollback the last migration you can do:
rake db:rollback
If you want to rollback a specific migration with a version you should do:
rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION
If the migration file you want to rollback was called db/migrate/20141201122027_create_some_table.rb, then the VERSION for that migration is 20141201122027, which is the timestamp of when that migration was created, and the command to roll back that migration would be:
rake db:migrate:down VERSION=20141201122027
To roll back all migrations up to a particular version (e.g. 20181002222222), use:
rake db:migrate VERSION=20181002222222
(Note that this uses db:migrate -- not db:migrate:down as in other answers to this question.)
Assuming the specified migration version is older than the current version, this will roll back all migrations up to, but not including, the specified version.
For example, if rake db:migrate:status initially displays:
(... some older migrations ...)
up 20181001002039 Some migration description
up 20181002222222 Some migration description
up 20181003171932 Some migration description
up 20181004211151 Some migration description
up 20181005151403 Some migration description
Running:
rake db:migrate VERSION=20181002222222
Will result in:
(... some older migrations ...)
up 20181001002039 Some migration description
up 20181002222222 Some migration description
down 20181003171932 Some migration description
down 20181004211151 Some migration description
down 20181005151403 Some migration description
Reference: Migrate or revert only some migrations
If it is a reversible migration and the last one which has been executed, then run rake db:rollback. And you can always use the version.
For example, if the migration file is 20140716084539_create_customer_stats.rb, the rollback command will be:
rake db:migrate:down VERSION=20140716084539
If you are using Ruby on Rails 3
Step: 1 (check the last migration)
bundle exec rake db:migrate:status
Step: 2 (roll back the last migration)
bundle exec rake db:rollback
Now, you can revert the migration with safety one by one.
For a specific migration
rails d migration <migration_name>
For reverting multiple migrations
bundle exec rake db:rollback STEP=n
where n is how many migrations you want to rollback.
Example: bundle exec rake db:rollback STEP=5
A migration file looks like this,
20221213051020_my_migrations
In this case, the model name should be MyMigration. The migration ends with a plural word, so it ends with migrations.
To roll back this particular migration, you have to understand that the first part of the migration name (number in front of the migration name) is the migration number.
To roll back this migration, just open the terminal and write,
rake db:migrate:down VERSION=migration_number
So finally, you have to actually type in the terminal to roll back this particular migration,
Write the below command on terminal to rollback a particular migration, upper command is just to explain you
rake db:migrate:down VERSION=20221213051020
Just remember that each migration has a different migration number, so watch carefully and copy paste or type manually.
Migrations change the state of the database using the command
bundle exec rake db:migrate
We can undo a single migration step using
bundle exec rake db:rollback
To go all the way back to the beginning, we can use
bundle exec rake db:migrate VERSION=0
As you might guess, substituting any other number for 0 migrates to that version number, where the version numbers come from listing the migrations sequentially.
Well, in rails 5 it's quite easy
rake db:migrate:status
or
rails db:migrate:status
It was modified to handle both the same way.
Then just pick which version you want to roll back
and then run
rake db:migrate VERSION=2013424230423
Make sure VERSION is all capital letters.
If you have a problem with any step of the migration or stuck in the middle simply, go to the migration file and comment out the lines that were already migrated.
If you want to rollback and migrate you can run:
rake db:migrate:redo
That's the same as:
rake db:rollback
rake db:migrate
I found these steps most useful.
To check for status, run rails db:migrate:status. Then you'll have a good view of the migrations you want to remove.
Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.
Next, if you want to remove or delete. Run rails d migration <migration_name>. This would clean up the versions you created.
After that's done, you can proceed to making new changes.
For a multiple databases configurations (RoR >= v6), you must append the database name in the command, like:
rails db:rollback:primary, where primary is the name of the database in your config/databases.yml file, to roll back the last migration. You can make usage of the STEPS attribute here, as usual.
rails db:migrate:down:primary VERSION=your_migration_timestamp, to revert only the provided migration version. Here primary is the name of the database too.
In addition:
When a migration you deployed long ago does not let you migrate a new one.
I work in a larger Ruby on Rails application with more than a thousand of migration files. And, it takes a month for us to ship a medium-sized feature. I was working on a feature and I had deployed a migration a month ago, and then in the review process the structure of migration and filename changed, now I try to deploy my new code, the build failed saying:
ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR: column "my_new_field" of relation "accounts" already exists
None of the above-mentioned solutions worked for me, because the old migration file was missing and the field I intended to create in my new migration file already existed in the database. The only solution that worked for me is:
I scped the file to the server
I opened the rails console
I required the file in the IRB session
then AddNewMyNewFieldToAccounts.new.down
And then I could run the deploy build again.
You can run down migration command to rollback the migration like below:
rake db:migrate:down VERSION=20100905201547
If you want to revert from the last migration, use the rake db:rollback command. It's working fine for me!