Search code examples
ruby-on-railsmodelspolymorphic-associationsrails-migrationsdestroy

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?

Solution

  • 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 :)