Changing the default ActiveRecord id from 0 to 1000000

吃可爱长大的小学妹 提交于 2019-12-23 14:25:23

问题


I'd like to change the minimum for the id of created objects from 1 to 1000. So when I create in rails my first model object it gets the ID 1000 and not 1.

Is there a way to set this in the schema/migration files?


回答1:


I am not familiar with MySQL, but for Postgres you can do something like this in your migration file:

class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :customers do |t|
      t.string :name
      t.timestamps

    end
    execute "SELECT setval('customers_id_seq', 1000);"
end

Note that the execute method call is made outside the create_table block.




回答2:


For MySQL use

class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :customers do |t|
      t.string :name
      t.timestamps

    end
    execute "ALTER TABLE customers AUTO_INCREMENT = 1000;"
end

This will have your auto_increment field (id) start at value 1000.



来源:https://stackoverflow.com/questions/2424431/changing-the-default-activerecord-id-from-0-to-1000000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!