Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing table from schema.rb

I had a Location model in my app, but then I went a step back with Git, when I didn't create the model yet, then after quite a while working on another branch I realized that the model had gone nowhere, and it is still in my schema. I tried to get rid of it but it still pops out of nowhere, although there are no add location migration files in my app. What is the best way to get rid of it and clean up my schema.rb?

UPDATE 1

Running

rails destroy model location

Gives me

  invoke  active_record
  remove    /Users/denis/Desktop/migration/templates/create_table_migration.rb
  remove    app/models/location.rb
  invoke    test_unit
  remove      test/models/location_test.rb
  remove      test/fixtures/locations.yml

And I can run it for the indefinite amounts, it will always give the same result

Running this migration:

class DropLocationsTable < ActiveRecord::Migration
  def self.up
    drop_table :locations
  end
end

Gives 0 result, after rake db:migrate the Locations appear in my schema.rb again

UPDATE 2

rails db
SQLite version 3.7.12 2012-04-03 19:43:07
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> SELECT * FROM locations;
sqlite> 
like image 680
The Whiz of Oz Avatar asked Dec 07 '25 03:12

The Whiz of Oz


2 Answers

If you want to really really remove it you should prepare a migration to drop the table.

If you just remove the model ActiveRecord will still find the table in db (and that's probably why you're seeing it in schema.rb - if I am right that you mean file and not db schema)

EDIT:

So I tried to reproduce this, and as a result I ended up with following order of commands.

  1. first drop the table (make a new migration with drop_table :locations and run it)
  2. then run rails destroy model location (you will get an error if you destroy model first)
  3. run rails c so Rails picks up the db change and updates schema.rb
like image 88
Mike Szyndel Avatar answered Dec 08 '25 15:12

Mike Szyndel


I find that it's easiest to use the Rails Console in solving this problem. Suppose you want to remove a 'comments' table from a blog application. You can do so by performing the following tasks from the command line (e.g., Terminal).

Step one:

$ rails console 

Step two:

$ ActiveRecord::Migration.drop_table(:comments)

Step three:

$ rake db:migrate

Go check your schema.rb to see that the table was removed.

like image 31
Vivekanand Panda Avatar answered Dec 08 '25 15:12

Vivekanand Panda