我找到了这个问题的"纯SQL"答案.是否有方法in Rails重置特定表的id字段

推荐答案

我根据hgimenez的答案和this other one给出了一个解决方案.

因为我通常使用Sqlite或PostgreSQL,所以我只为它们开发;但将其扩展到MySQL,应该不会太麻烦.

将其放入lib/中,并在初始值设定项上要求它:

# lib/active_record/add_reset_pk_sequence_to_base.rb
module ActiveRecord
  class Base
    def self.reset_pk_sequence
      case ActiveRecord::Base.connection.adapter_name
      when 'SQLite'
        new_max = maximum(primary_key) || 0
        update_seq_sql = "update sqlite_sequence set seq = #{new_max} where name = '#{table_name}';"
        ActiveRecord::Base.connection.execute(update_seq_sql)
      when 'PostgreSQL'
        ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
      else
        raise "Task not implemented for this DB adapter"
      end
    end     
  end
end

用法:

Client.count # 10
Client.destroy_all
Client.reset_pk_sequence
Client.create(:name => 'Peter') # this client will have id=1

编辑:因为最常见的情况是在清除数据库表之后,所以我建议查看database_cleaner.它自动处理ID重置.您可以告诉它只删除选定的表,如下所示:

DatabaseCleaner.clean_with(:truncation, :only => %w[clients employees])

Ruby-on-rails相关问答推荐

为Rails服务器推荐的交付类型

本地主机的上衣配置

如何将 ActionController::RoutingError 分类为 Sentry 中的错误

如何通过graphqlMutations 从rails销毁当前用户会话

Ruby on rails 查询不知道怎么写

验证模型属性大于另一个

比较 Rails 中的日期

Rails 路由到唯一索引

验证以确保唯一性但忽略空值?

使用 Rspec 测试 Rails 3.1 可安装引擎

在 Rails 中将毫秒转换为格式化日期

Rails 3 中图像路径的完整 url

SQLite3::BusyException

安装mysql2(0.4.8)时出错,Bundler无法继续

如何在 Rails 1.2.3 中使复选框默认为选中?

Rails 3.1 Sprockets 需要指令 - 有没有办法排除特定文件?

如何在同一个 Rails 控制器操作中处理多个 HTTP 方法

设计/Rails - 如何删除特定的 Flash 消息? (登录成功)

Sidekiq 在 docker-compose 上的 127.0.0.1:6379 (Errno::ECONNREFUSED) 上连接到 Redis 时出错

Vagrant上的Rails 4.2服务器端口转发不起作用