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?
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?
This is hard to set for the primary key with migrations because Rails puts it in automatically.
You can change any column later like this:
change_column :foobars, :something_id, 'bigint'
You can specify non-primary IDs as custom types in your initial migration like this:
create_table :tweets do |t|
t.column :twitter_id, 'bigint'
t.column :twitter_in_reply_to_status_id, 'bigint'
end
Where I have "bigint" you can put any text that your database would use for the database column type you want to use (e.g., "unsigned long").
If you need your id column to be a bigint, the easiest way to do it would be to create the table, then change the column in the same migration with change_column.
With PostgreSQL and SQLite, schema changes are atomic so this won't leave your database in a weird state if the migration fails. With MySQL you need to be more careful.
According to the Rails API documentation, the possible options for type are:
:string
:text
:integer
:float
:decimal
:datetime
:timestamp
:time
:date
:binary
:boolean
You can use :decimal, or you can execute a command directly if you need to:
class MyMigration
def self.up
execute "ALTER TABLE my_table ADD id LONG"
end
end
As wappos pointed out, you can use auxiliary options like :limit to tell ActiveRecord how large you want the column to be. So you would use the :int column with a larger :limit.
Rails 3, MySQL:
t.column :foobar, :int, :limit => 8
Does not give me a bigint, only an int. However,
t.column :twitter_id, 'bigint'
works fine. (Although it does tie me to MySQL.)