我如何在1 Rails重新启动记录id



我有一个rake任务来填充一个表。

如下:

namespace :db do
  desc  "fill in the database with icons data"
  task :populate_icons => :environment do 
    make_types
    make_templates
    make_categories
    make_greeting_icons
    make_user_icons
  end
end
  def make_types
    Type.delete_all
    types = %w{Classic Popular Children Animals}
    types.each do |type|   
      Type.create!(:name => type, :adult => false) #1
    end
  end

我不能删除数据库,因为有些表中会有用户数据。

当我重新播种表时,我需要将id重新启动为1。

我如何在Rails中做到这一点?

如果你正在使用PostgreSql,重新启动你的序列:

ALTER SEQUENCE table_id_seq RESTART 1;

你也可以通过模型连接来做:

MyModel.connection.execute('ALTER SEQUENCE my_models_id_seq RESTART 1')

对于mysql,试试下面的代码片段

ActiveRecord::Base.connection.execute('ALTER TABLE tablename AUTO_INCREMENT=1')

最新更新