I have a MySQL Database named Foo_development
. It has one table, named bars
.
$ mysql -e 'select * from Foo_development.bars'
+----+-------+---------------+---------------------+---------------------+
| id | name | email | created_at | updated_at |
+----+-------+---------------+---------------------+---------------------+
| 1 | Alice | Alice@bob.com | 2015-08-24 13:45:11 | 2015-08-24 13:45:11 |
+----+-------+---------------+---------------------+---------------------+
I'd like to create a Rails app that uses this database and this table. So I created an app and a model:
$ rails new Foo -d mysql
$ cd Foo
$ rails generate model Bar name:string email:string
That all worked just fine, although I had to edit config/database.yml
to connect to the appropriate MySQL host before generating the model.
I tried running my app and got an error:
$ rails server
ActiveRecord::PendingMigrationError
Migrations are pending. To resolve this issue, run:
bin/rake db:migrate RAILS_ENV=development
I tried running the migrations and got another error:
$ rake db:migrate
== 20150824204923 CreateBars: migrating ===
StandardError: An error has occurred, all later migrations canceled:
Mysql2::Error: Table 'bars' already exists
Didn't know what to do here, so I tried something I found on Google:
$ rake db:migrate:reset
== 20150824204923 CreateBars: migrated (0.0124s) ===
But now all my database data is gone :(
$ mysql -e 'select * from Foo_development.bars'
Empty set (0.00 sec)
What should I have done instead to avoid losing all of my data?
I'm assuming there must be some command besides rake db:migrate:reset
that would allow me to run the migrations without truncating the tables in the database, but I haven't found any.
I did look at these questions but they don't talk about preventing data loss, so this is not a duplicate.
If it matters, the Rails app is running from a different computer than the one which hosts the MySQL database. I'm trying to avoid import/export operations, because the databases that I'm working with (outside of this trivial example) have a million+ rows, but I suppose I'm willing to do that if that's the fastest method.
Edit: This question is similar, but it asks about sqlite3 and the answer involves importing the database from an external file (and I'm guessing there's a faster/more efficient way than that.)