如何使用单个ActiveRecord连接截断n个表 [英] How to truncate n tables with one single ActiveRecord connection

查看:19
本文介绍了如何使用单个ActiveRecord连接截断n个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个rake任务,以便从特定n个表中删除所有记录,并重置id列的值,以便在创建新记录时它的ID为1。
前面的问题Truncate table(s) with rails console对于完成单个表的工作很有用(如果任务的性能可以提高,我会使用delete_all代替destroy_all):

Model.delete_all
ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY")

如果我需要截断多个表,例如表table1table2table3,是否可以使用单个ActiveRecord连接,例如:

Model1.delete_all
Model2.delete_all
Model3.delete_all
ActiveRecord::Base.connection.execute("TRUNCATE #{table1, table2, table3} RESTART IDENTITY")

并因此避免建立多个ActiveRecord连接,如下例所示?

Model1.delete_all
Model2.delete_all
Model3.delete_all
ActiveRecord::Base.connection.execute("TRUNCATE #{table1} RESTART IDENTITY")
ActiveRecord::Base.connection.execute("TRUNCATE #{table2} RESTART IDENTITY")
ActiveRecord::Base.connection.execute("TRUNCATE #{table3} RESTART IDENTITY")

推荐答案

rails 6.0新增方法:TRUNCATE_TABLES

ActiveRecord::Base.connection.truncate_tables(:table1_name, :table2_name)

TRUNCATE_TABLES尚未提供API文档,它本质上是基于truncate方法

source code

  def truncate(table_name, name = nil)
    execute(build_truncate_statements(table_name), name)
  end

  def truncate_tables(*table_names) # :nodoc:
    return if table_names.empty?

    with_multi_statements do
      disable_referential_integrity do
        Array(build_truncate_statements(*table_names)).each do |sql|
          execute_batch(sql, "Truncate Tables")
        end
      end
    end
  end

rails 6.1已进行调整,以防止错误删除与迁移相关的表source code

  def truncate_tables(*table_names) # :nodoc:
    table_names -= [schema_migration.table_name, InternalMetadata.table_name]

    return if table_names.empty?

    with_multi_statements do
      disable_referential_integrity do
        statements = build_truncate_statements(table_names)
        execute_batch(statements, "Truncate Tables")
      end
    end
  end

这篇关于如何使用单个ActiveRecord连接截断n个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆