ActiveRecord自动增量值

Roh*_*hal 0 mysql activerecord ruby-on-rails

我在rails web应用程序上使用mysql的活动记录.

保存一些活动记录模型后,我注意到id字段增加了10.不应该是1吗?

如果我可以更改它是什么是rake或activerecord迁移命令

Rah*_*ngh 5

在rails控制台类型中

1.对于postgresql

ActiveRecord::Base.connection.execute("ALTER SEQUENCE table_name_id_seq RESTART WITH 1")
Run Code Online (Sandbox Code Playgroud)

2.对于mysql

ActiveRecord::Base.connection.execute("ALTER TABLE table_name AUTO_INCREMENT=1")
Run Code Online (Sandbox Code Playgroud)

其中table_name是您的实际表名

使用迁移

class SetAutoIncrement < ActiveRecord::Migration
  def self.up
    execute "ALTER TABLE table_name AUTO_INCREMENT=1"
  end

  def self.down
  end
end
Run Code Online (Sandbox Code Playgroud)