在迁移中更改自动增量值(PostgreSQL和SQLite3) [英] Change Autoincrement values in migration (PostgreSQL and SQLite3)
问题描述
我在Heroku上托管了一个项目,并希望更改表格的自动增量起始值。我在本地使用SQLite3,而Heroku使用PostgreSQL。
I have a project hosted on Heroku and would like to change a table's autoincrement start value. I'm using SQLite3 locally and Heroku uses PostgreSQL This is what I have in the migration:
class CreateMytable < ActiveRecord::Migration
def self.up
create_table :mytable do |t|
t.text :mytext
end
case ActiveRecord::Base.connection.adapter_name
when 'PostgreSQL'
execute 'ALTER SEQUENCE mytable_id_seq RESTART WITH 1000;'
when 'SQLite'
execute 'update sqlite_sequence set seq = 1000 where name = "mytable";'
else
end
end
def self.down
drop_table :mytable
end
end
迁移在本地运行,但是SQLite似乎只是忽略该更改,尽管它在Heroku上有效。我在做什么错了?
Locally the migration runs but SQLite seems to just ignore the change, it works on Heroku though. What am I doing wrong?
推荐答案
老实说,听起来这并不属于迁移。您可以将以下内容添加到初始化程序中,以使其成为方便的基类方法以作为任务的一部分进行调用:
Honestly, it doesn't sound like this belongs in a migration. You could add the following to an initializer to make a handy Base class method to call as part of a task, though:
ActiveRecord::Base.class_eval do
def self.reset_autoincrement(options={})
options[:to] ||= 1
case self.connection.adapter_name
when 'MySQL'
self.connection.execute "ALTER TABLE #{self.table_name} AUTO_INCREMENT=#{options[:to]}"
when 'PostgreSQL'
self.connection.execute "ALTER SEQUENCE #{self.table_name}_id_seq RESTART WITH #{options[:to]};"
when 'SQLite'
self.connection.execute "UPDATE sqlite_sequence SET seq=#{options[:to]} WHERE name='#{self.table_name}';"
else
end
end
end
然后只需将以下内容作为任务的一部分运行或直接在控制台中运行即可:
Then just run the following as part of a task or right in the console:
Mytable.reset_autoincrement(:to => 1000)
请确保检查此方便的答案以了解为什么sqlite可能无法正常工作。
Make sure to check this handy answer as to why the sqlite may not be working.
这篇关于在迁移中更改自动增量值(PostgreSQL和SQLite3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!