How can I restart record ids at 1 Rails
I have a rake task to populate a table.
as follows:
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
I can't drop the database as some tables will have user data in them.
I ne开发者_如何学Pythoned to restart the id's at 1 when I re-seed the tables.
How can I do this in Rails?
If you are using PostgreSql, to restart your sequence:
ALTER SEQUENCE table_id_seq RESTART 1;
You can also do that through the model connection:
MyModel.connection.execute('ALTER SEQUENCE my_models_id_seq RESTART 1')
For mysql try this snippet
ActiveRecord::Base.connection.execute('ALTER TABLE tablename AUTO_INCREMENT=1')
精彩评论