Ruby-on-rails 删除 rails 中的模型(与“rails g 模型标题...”相反)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7105373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:48:07  来源:igfitidea点击:

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

ruby-on-railsrubymodelmigration

提问by Colbern

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

How can I completely remove this model? Thanks

我怎样才能完全删除这个模型?谢谢

回答by Mikhail Nikalyukin

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

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

生成模型时,它会创建数据库迁移。如果在该模型上运行 'destroy',它将删除迁移文件,但不会删除数据库表。所以在运行之前

bundle exec rake db:rollback

回答by fl00r

Try this

尝试这个

rails destroy model Rating

It will remove model, migration, tests and fixtures

它将删除模型、迁移、测试和夹具

回答by Jenny Lang

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

回答by Govind shaw

  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
    
  1. 删除迁移(如果您已经迁移了迁移)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. 删除模型

    rails d model name  #name => Your model name
    

回答by Powers

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

这是适用于 Rails 5 的 Jenny Lang 答案的不同实现。

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:migratewill drop the table. If you run rails db:rollback, Rails will throw a ActiveRecord::IrreversibleMigrationerror.

运行rails db:migrate将删除表。如果你运行rails db:rollback,Rails 会抛出一个ActiveRecord::IrreversibleMigration错误。