Sunday, May 1, 2011

How to set an initial id value on a create_table?

I want to get the auto incrementing id column for a create_table rails command to start at 500.

I've found examples of how to set the initial auto_increment id value in sql:

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;

So I looked at the Rails API and saw these options on the create_table method:

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.

Not what I need... I tried this without success:

:options => {:auto_increment => 500}

Anyone know how to get the auto incrementing id column for this statement to start at 500:

create_table :contents do |t|
  t.string  :type,                :null => false
  t.string  :name,                :null => false
end
From stackoverflow
  • This is just a guess, but have you tried inserting (then deleting) a row in the table at ID of 499?

  • The SQL statement to set this would be:

    ALTER TABLE student AUTO_INCREMENT = 500;
    
  • There are a number of ways to do this, some RDBMS specific (you don't specify what RBDMS you're using, but the MyIsam table indicates MySQL).

    But it has a bad smell; you shouldn't care anything about a synthetic key other than that it is unique and monotonically increasing. That you do care suggests there may be a larger problem.

  • Try this:

    create_table(:student, :options => 'AUTO_INCREMENT = 500') do |t|
      t.column :name, :string, :limit => 50
      # Other fields here   
    end
    
    Matt : That did it! Thanks!
    John Topley : Good - I wasn't actually able to test it when I posted it! :-)

0 comments:

Post a Comment