Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use long id in Rails applications?

How can I change the (default) type for ActiveRecord's IDs? int is not long enough, I would prefer long. I was surprised that there is no :long for the migrations - does one just use some decimal?

like image 769
Björn Avatar asked Jun 30 '09 22:06

Björn


2 Answers

Credits to http://moeffju.net/blog/using-bigint-columns-in-rails-migrations

class CreateDemo < ActiveRecord::Migration   def self.up     create_table :demo, :id => false do |t|       t.integer :id, :limit => 8     end   end end 
  • See the option :id => false which disables the automatic creation of the id field
  • The t.integer :id, :limit => 8 line will produce a 64 bit integer field
like image 160
Notinlist Avatar answered Sep 21 '22 12:09

Notinlist


To set the default primary key column type, the migration files are not the place to mess with.

Instead, just stick this at the bottom of your config/environment.rb

ActiveRecord::ConnectionAdapters::MysqlAdapter::NATIVE_DATABASE_TYPES[:primary_key] = "BIGINT UNSIGNED DEFAULT NULL auto_increment PRIMARY KEY" 

And all your tables should be created with the intended column type for id:

+--------------+---------------------+------+-----+---------+----------------+ | Field        | Type                | Null | Key | Default | Extra          | +--------------+---------------------+------+-----+---------+----------------+ | id           | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |  

After you've done what you've set out to do... the next question is probably "How do I make my foreign key columns the same column type?" since it does not make sense to have primary key people.id as bigint(20) unsigned, and person_id be int(11) or anything else?

For those columns, you can refer to the other suggestions, e.g.

t.column :author_id, 'BIGINT UNSIGNED' t.integer :author_id, :limit => 8 

UPDATE: @Notinlist, to use arbitrary column for primary key on arbitrary tables you need to do the create_table-change_column dance:

create_table(:users) do |t|   # column definitions here.. end change_column :users, :id, :float # or some other column type 

e.g. if I wanted guid instead of auto-increment integers,

create_table(:users, :primary_key => 'guid') do |t|   # column definitions here.. end change_column :users, :guid, :string, :limit => 36 
like image 44
choonkeat Avatar answered Sep 24 '22 12:09

choonkeat