Colbern
Colbern

Reputation: 1321

Removing a model in rails (reverse of "rails g model Title...")

rails g model Rating user_id:integer message:string value:integer

How can I completely remove this model? Thanks

Upvotes: 132

Views: 146476

Answers (6)

Haseeb A
Haseeb A

Reputation: 6122

If you are interested in reversible migration to drop a table

class DropProductsTable < ActiveRecord::Migration[7.0]
  def change
    drop_table :products do |t|
      t.string :name
      t.text :description
      t.decimal :price, precision: 8, scale: 2
      t.timestamps
 # Rest of the stuff like indexes. Consider copying directly from schema.rb
    end
  end
end

Upvotes: 0

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run

bundle exec rails db:rollback
rails destroy model <model_name>

For rails versions before 5.0 and higher use rake instead of rails

bundle exec rake db:rollback   
rails destroy model <model_name>

Upvotes: 217

Powers
Powers

Reputation: 19308

Here's a different implementation of Jenny Lang's answer that works for Rails 5.

First create the migration file:

bundle exec be rails g migration DropEpisodes

Then populate the migration file as follows:

class DropEpisodes < ActiveRecord::Migration[5.1]
  def change
    drop_table :episodes
  end
end

Running rails db:migrate will drop the table. If you run rails db:rollback, Rails will throw a ActiveRecord::IrreversibleMigration error.

Upvotes: 5

Govind shaw
Govind shaw

Reputation: 427

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

Upvotes: 25

Jenny Lang
Jenny Lang

Reputation: 401

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

Upvotes: 34

fl00r
fl00r

Reputation: 83680

Try this

rails destroy model Rating

It will remove model, migration, tests and fixtures

Upvotes: 65

Related Questions