[英]Rails reset ALL Postgres sequences?
The following works in the Rails 3 console to reset Postgres sequences: 以下在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')
Is there a command that would reset ALL of them instead of having to do each one individually? 是否有一个命令可以重置所有这些命令而不必单独执行每个命令?
Thanks for the help! 谢谢您的帮助!
This is easier 这更容易
ActiveRecord::Base.connection.tables.each do |t|
ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
I found one way to do it from this posting: Reset PostgreSQL 我从这篇文章中找到了一种方法: 重置PostgreSQL
I placed the following into seed.rb
and ran rake db:seed
我将以下内容放入
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.