Ruby-on-rails 如何清除 Rails seed.rb 中的整个数据库

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

how to clear whole database in Rails seeds.rb

ruby-on-rails

提问by chodorowicz

What is the best way to accomplish this? As for now I'm using:

实现这一目标的最佳方法是什么?至于现在我正在使用:

Role.delete_all
User.delete_all
...

but how to clear habtm talbes? Like roles_users

但是如何清除habtm talbes?喜欢角色_用户

Updated Answer

更新答案

I think ream88 response answers my question most precisely, but probably the bestidea is to follow coreyward suggestion to use separate rake tasks and leave seeds.rb only for seeding data.

我认为 ream88 的回答最准确地回答了我的问题,但最好的想法可能是遵循 coreyward 的建议,使用单独的 rake 任务,并只将 seed.rb 用于播种数据。

This is updated answer from ream88 which doesn't delete schema_migrationstable.

这是 ream88 的更新答案,它不删除schema_migrations表。

ActiveRecord::Base.establish_connection
ActiveRecord::Base.connection.tables.each do |table|
  # MySQL
  ActiveRecord::Base.connection.execute("TRUNCATE #{table}") unless table == "schema_migrations"

  # SQLite
  # ActiveRecord::Base.connection.execute("DELETE FROM #{table}") unless table == "schema_migrations"
end

Thanks a lot for help!

非常感谢您的帮助!

采纳答案by Mario Uher

I definitely agree with @coreyward's answer, but if you really want to clear all tables inside your seeds.rbfile, this snippet will do the job:

我绝对同意@coreyward 的回答,但如果您真的想清除seeds.rb文件中的所有表,此代码段将完成这项工作:

ActiveRecord::Base.establish_connection
ActiveRecord::Base.connection.tables.each do |table|
  next if table == 'schema_migrations'

  # MySQL and PostgreSQL
  ActiveRecord::Base.connection.execute("TRUNCATE #{table}")

  # SQLite
  # ActiveRecord::Base.connection.execute("DELETE FROM #{table}")
end

回答by coreyward

First of all, I don't think it's a good idea to mix concerns like this. The seeds.rbfile is intended to seed the database with data, not reset it. There is already a rake task for resetting a database (rake db:migrate:reset) that just runs rake db:drop db:create db:migrate. If you're wanting to seed a fresh database, you can just run rake db:reset db:seed.

首先,我认为将这样的问题混合在一起并不是一个好主意。该seeds.rb文件旨在为数据库提供数据,而不是重置它。已经有一个用于重置rake db:migrate:reset刚刚运行的数据库 ( )的 rake 任务rake db:drop db:create db:migrate。如果你想为一个新的数据库做种子,你可以运行rake db:reset db:seed.

回答by Thariq Shihipar

You can try Rake::Task["db:reset"]invoke.

你可以试试Rake::Task["db:reset"]调用。

rake db:reset is just a rake task you can call to reset the database, using Rake::Task lets you call it from a script.

rake db:reset 只是一个 rake 任务,您可以调用它来重置数据库,使用 Rake::Task 可以让您从脚本中调用它。