完成此任务的最佳方法是什么?至于现在,我正在使用:
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
.
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)
归档时间: |
|
查看次数: |
19980 次 |
最近记录: |