如何在Rails seeds.rb中清除整个数据库

cho*_*icz 23 ruby-on-rails

完成此任务的最佳方法是什么?至于现在,我正在使用:

Role.delete_all
User.delete_all
...
Run Code Online (Sandbox Code Playgroud)

但如何清除habtm talbes?像roles_users一样

更新的答案

我认为ream88的回答最准确地回答了我的问题,但可能是bestidea遵循coreyward建议来使用单独的rake任务并将seeds.rb留给播种数据.

这是来自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
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助!

cor*_*ard 44

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

  • 我的立场得到了纠正 - 它确实也是种子.我更喜欢这是一个更明确的操作,因此您可以重置并将所有表都清空. (3认同)

Mar*_*her 16

我绝对同意@ 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
Run Code Online (Sandbox Code Playgroud)