以下在Rails 3控制台中可以重置Postgres序列:
ActiveRecord::Base.connection.reset_pk_sequence!('menucontrols')
ActiveRecord::Base.connection.reset_pk_sequence!('statuscodes')
ActiveRecord::Base.connection.reset_pk_sequence!('wostatuses')
ActiveRecord::Base.connection.reset_pk_sequence!('taskstatuses')
ActiveRecord::Base.connection.reset_pk_sequence!('priorities')
ActiveRecord::Base.connection.reset_pk_sequence!('actcodes')
是否有一个命令可以重置所有这些命令而不必单独执行每个命令?
感谢您的帮助!
答案 0 :(得分:41)
这更容易
ActiveRecord::Base.connection.tables.each do |t|
ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
答案 1 :(得分:11)
我从这篇帖子中找到了一种方法: Reset PostgreSQL
我将以下内容放入seed.rb
并运行rake db:seed
ActiveRecord::Base.connection.tables.each do |table|
result = ActiveRecord::Base.connection.execute("SELECT id FROM #{table} ORDER BY id DESC LIMIT 1") rescue ( puts "Warning: not procesing table #{table}. Id is missing?" ; next )
ai_val = result.any? ? result.first['id'].to_i + 1 : 1
puts "Resetting auto increment ID for #{table} to #{ai_val}"
ActiveRecord::Base.connection.execute("ALTER SEQUENCE #{table}_id_seq RESTART WITH #{ai_val}")
end