Wednesday, January 26, 2011

how to set primary key and autoincrement on non id column using rails 3 -- sqlite

sqlite_adopter uses
       def default_primary_key_type
          if supports_autoincrement?
            'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'
          else
            'INTEGER PRIMARY KEY NOT NULL'
          end
        end
and under the create table definition the line says:
table_definition.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false

that means we should not set :id => false ... many people will do to avoid id column..  this is fine
but if you want  other column as primary key add at table definition not at column definition.(dont add :id => false)..

adding primary_key at table definition will take care of removing id column.  the following line will also add t ocolumn definition
  'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'
 ofcourse based on sqlite3 version...

      def supports_autoincrement? #:nodoc:
        sqlite_version >= '3.1.0'
      end
 Note: so autoincrement for :primary_key is hard coded
sample:
create_table :students, :primary_key => student_id do |t|
   t.string :name
end
it generates students table as follows;
  students;
                  student_id : primary key autoincrement
                 name :   varchar


This is for what i am using version of rails : 3.0.3