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

发布于 2024-12-09 13:06:42 字数 307 浏览 0 评论 0原文

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

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

你们有什么事情要给我吗?

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

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

Do you guys have somehting for me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

最丧也最甜 2024-12-16 13:06:42

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

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

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

使用该 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

就是这样。您还可以直接使用 db/seeds.rb 文件中的 DatabaseCleaner.clean_with :truncation 行,这样您就不会忘记在播种前截断数据库。

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_cleaner gem. Here're the steps.

In your Gemfile (execute bundle after modifying):

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 :truncation will truncate the database. Adding it to a rake task is trivial:

# 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 :truncation line inside your db/seeds.rb file directly so that you don't forget to truncate the database before seeding.

往事风中埋 2024-12-16 13:06:42

因此,我将链接的示例编辑为:

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

此示例基于 Chris Ledet 的以下代码(谢谢),并适用于 Rails 3.X

感谢所有提示。

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.

Thanks for all hints.

眼眸里的快感 2024-12-16 13:06:42

在 Rails 6 中截断数据库

rails db:truncate_all  

To truncate db in Rails 6

rails db:truncate_all  
小嗷兮 2024-12-16 13:06:42

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

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

According to Chris Ledet answer, this becomes much simpler:

ActiveRecord::Base.connection.tables.each do |table|
    ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table};")
end
惜醉颜 2024-12-16 13:06:42

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

rake db:migrate VERSION=0

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

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

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

此外,您可以随时运行假设您的 schema.rb 是最新的,如下所示:

rake db:schema:load

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

DatabaseCleaner.clean_with :truncation

You could always migrate to version 0, like so:

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 down migrations to work properly.

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

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

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

rake db:schema:load

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

DatabaseCleaner.clean_with :truncation
触ぅ动初心 2024-12-16 13:06:42

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

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

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

tables = ActiveRecord::Base.connection.tables
tables.each do |tbl|
 # "users" => User
 tbl.classify.constantize.destroy_all
end
意犹 2024-12-16 13:06:42

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文