【问题标题】:How to set an initial id value on a create_table?如何在 create_table 上设置初始 id 值?
【发布时间】:2009-04-23 23:42:59
【问题描述】:

我想为 create_table rails 命令获取从 500 开始的自动递增 id 列。

我找到了如何在 sql 中设置初始 auto_increment id 值的示例:

CREATE TABLE student ( id int(2) NOT NULL auto_increment, name varchar(50) NOT NULL default '', class varchar(10) NOT NULL default '', mark int(3) NOT NULL default '0', sex varchar(6) NOT NULL default 'male', UNIQUE KEY id (id) ) auto_increment=100000 TYPE=MyISAM; 

所以我查看了 Rails API 并在 create_table 方法上看到了这些选项:

The options hash can include the following keys:

:id
    Whether to automatically add a primary key column. Defaults to true. Join tables for has_and_belongs_to_many should set :id => false. 
:primary_key
    The name of the primary key, if one is to be added automatically. Defaults to id. 
:options
    Any extra options you want appended to the table definition. 
:temporary
    Make a temporary table. 
:force
    Set to true to drop the table before creating it. Defaults to false. 

不是我需要的……我试过了但没有成功:

:options => {:auto_increment => 500}

任何人都知道如何让这条语句的自动递增 id 列从 500 开始:

create_table :contents do |t|
  t.string  :type,                :null => false
  t.string  :name,                :null => false
end

【问题讨论】:

    标签: sql ruby-on-rails


    【解决方案1】:

    试试这个:

    create_table(:student, :options => 'AUTO_INCREMENT = 500') do |t|
      t.column :name, :string, :limit => 50
      # Other fields here   
    end
    

    【讨论】:

    • 好 - 我发布它时实际上无法测试它! :-)
    【解决方案2】:

    设置它的 SQL 语句是:

    ALTER TABLE student AUTO_INCREMENT = 500;
    

    【讨论】:

      【解决方案3】:

      有很多方法可以做到这一点,一些 RDBMS 特定的(您没有指定您使用的 RBDMS,但 MyIsam 表指示 MySQL)。

      但它有难闻的气味;除了它是唯一且单调递增的之外,您不应该关心合成密钥。你的关心表明可能存在更大的问题。

      【讨论】:

        【解决方案4】:

        这只是一个猜测,但您是否尝试过在 ID 为 499 的表中插入(然后删除)一行?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-06
          • 2019-07-11
          • 2021-10-18
          • 2022-12-10
          • 2023-01-30
          • 2016-11-27
          • 1970-01-01
          • 2017-03-12
          相关资源
          最近更新 更多