Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Model and Table so can start again in Rails

I created a model for comments at the start of a project, but have now come to the realisation I need to create some polymorphic relations so I can use comments with a number of other models as well. Considering the the code I already have etc, I'm thinking it might be easier for me to just start again from scratch so I can build all the views/controllers etc in the correct way for my new polymorphic world.

I see that I can run rails destroy model comments to achieve this but I have two questions on that:

  1. Will this delete the model, migrations AND the actual DB table?
  2. What are the implications when I want to create a new model with the exact same name?
like image 309
Simon Cooper Avatar asked Apr 11 '17 18:04

Simon Cooper


2 Answers

In order to completely remove all columns & tables that migration has created you need to run:

rails db:migrate:down VERSION=012345678 (where 012345678 should be the version number of your migration)

.............................

rails destroy model Comments

will delete your Model, pending migration, tests and fixtures

So destroy it's the opposite of generate:

$ bin/rails destroy model Oops
      invoke  active_record
      remove    db/migrate/20120528062523_create_oops.rb
      remove    app/models/oops.rb
      invoke    test_unit
      remove      test/models/oops_test.rb
      remove      test/fixtures/oops.yml

And, you can now create a new Model with the same name, as there's no trace of your previous one :)

like image 199
catch22 Avatar answered Nov 07 '22 19:11

catch22


If you have already migrated the database after creating the model:

First, rollback the changes to the database:

rake db:migrate:down VERSION=20100905201547

where version is the timestamp identifying the migration. For example, if your migration file is called 20170411182948_create_comments.rb then your version parameter should be 20170411182948

Then run

rails destroy model comments

The first command will delete the table from the actual database. The second command will delete the model and the migration file. Make sure you run them in that order as the first command is dependent on the migration file to perform the rollback (which is deleted during the second command).

If you have have not migrated the database:

The table would not have been added to your database. You can go ahead and delete your model and migration files manually or use the destroy command.

like image 26
Zain Avatar answered Nov 07 '22 20:11

Zain