【问题标题】:truncate and restart identity of a set of tables截断并重新启动一组表的标识
【发布时间】:2017-01-24 13:17:55
【问题描述】:

我的应用程序使用Postgresql。
我需要从一组表(table1 到 table4)中删除所有行,然后使用 rb 文件中的一个命令重新启动 id。

在Postgresql documentation 中,我发现带有 RESTART IDENTITY 的 TRUNCATE 可以按以下方式完成工作:

TRUNCATE table1, table2, table3, table4 RESTART IDENTITY;

根据 Stackoverflow 的How to restart id counting on a table in PostgreSQL after deleting some previous data?,我可以使用以下命令:

ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY")

那么把这两个文档放在一起,使用下面的命令是否正确:

ActiveRecord::Base.connection.execute("TRUNCATE table1, table2, table3, table4 RESTART IDENTITY")

考虑到在API dock 文档中connection 方法被报告为已弃用或移动?

【问题讨论】:

    标签: ruby-on-rails postgresql rails-activerecord truncation


    【解决方案1】:

    现在推荐的方法是使用ActiveRecord::Base.connection_pool.with_connection 块。

    ActiveRecord::Base.connection_pool.with_connection do |conn|
      conn.execute("TRUNCATE table1, table2, table3, table4 RESTART IDENTITY")
    end
    

    【讨论】:

      猜你喜欢
      • 2014-08-16
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2021-01-07
      相关资源
      最近更新 更多