postgresql Rake 任务截断 Rails 3 中的所有表

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

Rake task to truncate all tables in Rails 3

sqlruby-on-rails-3postgresqlrake

提问by lzap

I would like to have a rake task for truncating all the tables. I have found oneon the internet, but it is supposed only for Rails 2 and does not work for Rails 3(problem is in getting a database connection).

我想要一个截断所有表的耙任务。我在互联网上找到了一个,但它只适用于 Rails 2,不适用于Rails 3(问题在于获取数据库连接)。

rake db:resetis not an option, because I am using PostgreSQL and it also drops the user. Therefore migration fails. I only want to clear the data.

rake db:reset不是一个选项,因为我使用的是 PostgreSQL 并且它也会删除用户。因此迁移失败。我只想清除数据。

Do you guys have somehting for me?

你们有事要找我吗?

回答by kikito

I've found this via google, and then I got a much simpler solution than the one approved, so here it is: Use the database_cleanergem. Here're the steps.

我通过谷歌找到了这个,然后我得到了一个比批准的更简单的解决方案,所以这里是:使用database_cleanergem。这是步骤。

In your Gemfile (execute bundle after modifying):

在您的 Gemfile 中(修改后执行包):

gem 'database_cleaner' # you might want to limit this to the dev and staging group

With that gem in place, the statement DatabaseCleaner.clean_with :truncationwill truncate the database. Adding it to a rake task is trivial:

有了这个 gem,该语句DatabaseCleaner.clean_with :truncation将截断数据库。将它添加到 rake 任务是微不足道的:

# tasks/db/clean.rake

namespace :db do

  desc "Truncate all existing data"
  task :truncate => "db:load_config" do
    DatabaseCleaner.clean_with :truncation
  end

end

That's it. You can also use the DatabaseCleaner.clean_with :truncationline inside your db/seeds.rbfile directly so that you don't forget to truncate the database before seeding.

而已。您也可以直接DatabaseCleaner.clean_with :truncationdb/seeds.rb文件中使用该行,以免在播种前忘记截断数据库。

回答by lzap

So I edited the linked example into this:

所以我将链接的示例编辑为:

namespace :db do
  desc "Truncate all existing data"
  task :truncate => "db:load_config" do
   begin
    config = ActiveRecord::Base.configurations[::Rails.env]
    ActiveRecord::Base.establish_connection
    case config["adapter"]
      when "mysql", "postgresql"
        ActiveRecord::Base.connection.tables.each do |table|
          ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
        end
      when "sqlite", "sqlite3"
        ActiveRecord::Base.connection.tables.each do |table|
          ActiveRecord::Base.connection.execute("DELETE FROM #{table}")
          ActiveRecord::Base.connection.execute("DELETE FROM sqlite_sequence where name='#{table}'")
        end                                                                                                                               
       ActiveRecord::Base.connection.execute("VACUUM")
     end
    end
  end
end

This example is based on Chris Ledet's code bellow (thanks) and works with Rails 3.X.

此示例基于 Chris Ledet 的代码波纹管(谢谢)并与Rails 3.X 一起使用

Thanks for all hints.

感谢所有提示。

回答by Felsangom

According to Chris Ledet answer, this becomes much simpler:

根据 Chris Ledet 的回答,这变得简单多了:

ActiveRecord::Base.connection.tables.each do |table|
    ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table};")
end

回答by thekingoftruth

You could always migrate to version 0, like so:

您始终可以迁移到版本 0,如下所示:

rake db:migrate VERSION=0

That way you don't even have to truncate your tables, and you can then migrate again. The only catch is that you need your downmigrations to work properly.

这样你甚至不必截断你的表,然后你可以再次迁移。唯一的问题是您需要down迁移才能正常工作。

This solution doeswork in rails 3, despite the fact that the versions are timestamp-based.

尽管版本是基于时间戳的,但该解决方案确实适用于 rails 3。

This solution is as seen here: https://stackoverflow.com/a/1196822/241367

此解决方案如下所示:https: //stackoverflow.com/a/1196822/241367

Additionally, you could always run the following, assuming your schema.rbis up to date:

此外,假设您schema.rb是最新的,您始终可以运行以下命令:

rake db:schema:load

And as @kikito suggests, you can run database_cleaner(it's what cucumberand rspeclike to use between tests) like so:

正如@kikito 所建议的那样,您可以像这样运行database_cleaner(这是在测试之间使用的cucumberrspec喜欢使用的):

DatabaseCleaner.clean_with :truncation

回答by Dany Alves

To truncate db in Rails 6

在 Rails 6 中截断 db

rails db:truncate_all  

回答by Chris Ledet

This will get all of the tables in your database, find a model associated with that table and call #destroy_all.

这将获取数据库中的所有表,找到与该表关联的模型并调用 # destroy_all

tables = ActiveRecord::Base.connection.tables
tables.each do |tbl|
 # "users" => User
 tbl.classify.constantize.destroy_all
end

回答by Ravikanth Andhavarapu

The answer given by lzap has one specific problem. Rails wants to run all the migrations again. The following code is as suggested by Anthony Alberto and it works. This addition checks with the schema_migrations table

lzap 给出的答案有一个特定的问题。Rails 想再次运行所有迁移。以下代码是由 Anthony Alberto 建议的,它可以工作。此添加检查 schema_migrations 表

namespace :db do
  desc "Truncate all existing data"
  task :truncate => "db:load_config" do
   begin
    config = ActiveRecord::Base.configurations[::Rails.env]
    ActiveRecord::Base.establish_connection
    case config["adapter"]
      when "mysql", "postgresql"
        ActiveRecord::Base.connection.tables.each do |table|
          ActiveRecord::Base.connection.execute("TRUNCATE #{table}") if table != "schema_migrations"
        end
      when "sqlite", "sqlite3"
        ActiveRecord::Base.connection.tables.each do |table|
          ActiveRecord::Base.connection.execute("DELETE FROM #{table}") if table != "schema_migrations"
          ActiveRecord::Base.connection.execute("DELETE FROM sqlite_sequence where name='#{table}'") if table != "schema_migrations"
        end                                                                                                                               
       ActiveRecord::Base.connection.execute("VACUUM")
     end
    end
  end
end