How to use long id in Rails applications?

后端 未结 11 1544
天涯浪人
天涯浪人 2020-11-30 22:24

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 on

11条回答
  •  心在旅途
    2020-11-30 22:56

    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.

提交回复
热议问题