开发者

how to clear whole database in Rails seeds.rb

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

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.

This is updated answer from ream88 which doesn't 开发者_如何学运维delete schema_migrations table.

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!


First of all, I don't think it's a good idea to mix concerns like this. The seeds.rb file 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.


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

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


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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜