How to turn off auto_increment in Rails Active Record

后端 未结 7 1712
日久生厌
日久生厌 2020-12-10 13:00

Is it possible to create primary key without auto_increment flag in ActiveRecord?

I can\'t do

create table :blah, :id          


        
7条回答
  •  庸人自扰
    2020-12-10 13:33

    Okay, the question is old and the OP did not specify versions. None of the answers given here worked for me with these versions:

    mysql2 0.3.11
    rails 3.2.13 
    mysql 5.5
    

    I ended up going for this:

    class SomeMigration < ActiveRecord::Migration
      # emulate a primary_key column without auto-increment
      # the solution here is to use a non-null integer id column with a unique index
      # this is semantically different from PRIMARY KEY in mysql but not
      # _too_ functionally different, the only difference is that mysql enforces
      # no-more-than-one-primary-key but allows >1 unique index
      def up
        create_table :foobars, :id => false do |t|
          t.integer :id, :null => false
          t.string :name
        end
        add_index :foobars, :id, :unique => true
      end
    end
    

    I hope that saves someone out there from spending time tracking this down, or worse ... using the answer without checking what it does to the db ... because the result of using either sojourner's or jim's answers (with my versions of the dependencies) is that the migration runs fine but NULL ids are allowed, and duplicate ids are allowed. I did not try Shep's answer because I don't like the idea of db/schema.rb being inconsistent (+1 to Shep for being explicit about that shortcoming, sometimes that'd be a Bad Thing)

    I'm not sure the significance of this, but with this solution, mysql describe shows it as a primary key, same as an AR table with default :id ... as in:

    table with AR default :id

    +---------------------+--------------+------+-----+---------+----------------+
    | Field               | Type         | Null | Key | Default | Extra          |
    +---------------------+--------------+------+-----+---------+----------------+
    | id                  | int(11)      | NO   | PRI | NULL    | auto_increment |
    

    table with my solution:

    +--------------+--------------+------+-----+---------+-------+
    | Field        | Type         | Null | Key | Default | Extra |
    +--------------+--------------+------+-----+---------+-------+
    | id           | int(11)      | NO   | PRI | NULL    |       |
    

    which is sort of interesting because the SQL generated by the migration with my solution does not include "PRIMARY KEY" (of course) ... but with AR default :id it does ... so it seems mysql, at least for describe treats a non-null unique-indexed key as a primary key

    HTH someone

提交回复
热议问题