Ruby-on-rails 删除数据库表中的所有记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5322298/
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 00:41:22  来源:igfitidea点击:

Deleting all records in a database table

ruby-on-railsrubydatabaseruby-on-rails-3

提问by Justin Meltzer

How do I delete all records in one of my database tables in a Ruby on Rails app?

如何在 Ruby on Rails 应用程序中删除其中一个数据库表中的所有记录?

回答by HakonB

If you are looking for a way to it without SQL you should be able to use delete_all.

如果您正在寻找一种无需 SQL 的方法,您应该可以使用 delete_all。

Post.delete_all

or with a criteria

或有标准

Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"

See herefor more information.

请参阅此处了解更多信息。

The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.

记录被删除而不先加载它们,这使得它非常快,但会破坏计数器缓存等功能,这些功能取决于删除时要执行的 rails 代码。

回答by lebreeze

To delete via SQL

通过 SQL 删除

Item.delete_all # accepts optional conditions

Item.delete_all # accepts optional conditions

To delete by calling each model's destroy method (expensive but ensures callbacks are called)

通过调用每个模型的 destroy 方法删除(昂贵但确保调用回调)

Item.destroy_all # accepts optional conditions

Item.destroy_all # accepts optional conditions

All here

在这里

回答by KensoDev

if you want to completely empty the database and not just delete a model or models attached to it you can do:

如果您想完全清空数据库,而不仅仅是删除一个或多个附加到它的模型,您可以执行以下操作:

rake db:purge

you can also do it on the test database

你也可以在测试数据库上做

rake db:test:purge

回答by dfaulken

If you mean delete every instance of all models, I would use

如果您的意思是删除所有模型的每个实例,我会使用

ActiveRecord::Base.connection.tables.map(&:classify)
  .map{|name| name.constantize if Object.const_defined?(name)}
  .compact.each(&:delete_all)

回答by Philip

BlogPost.find_each(&:destroy)

回答by Simon Ninon

More recent answer in the case you want to delete every entries in every tables:

在您想要删除每个表中的每个条目的情况下的最新答案:

def reset
    Rails.application.eager_load!
    ActiveRecord::Base.descendants.each { |c| c.delete_all unless c == ActiveRecord::SchemaMigration  }
end

More information about the eager_loadhere.

有关eager_load此处的更多信息。

After calling it, we can access to all of the descendants of ActiveRecord::Baseand we can apply a delete_allon all the models.

调用它后,我们可以访问它的所有后代,ActiveRecord::Base并且可以delete_all在所有模型上应用 a 。

Note that we make sure not to clear the SchemaMigration table.

请注意,我们确保不要清除 SchemaMigration 表。

回答by stef

If your model is called BlogPost, it would be:

如果您的模型名为 BlogPost,它将是:

BlogPost.all.map(&:destroy)