4

我想通过rails迁移在我的表中定义如下主键ID

id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT

我正在使用 mysql 数据库。

4

4 回答 4

4

如果您希望避免在迁移中使用自定义 SQL,这也可以:

create_table(:user, id: false,  primary_key: :id) do |t|
  t.primary_key :id, :unsigned_integer, null: false, default: :null, auto_increment: true
  t.string :name
end
于 2016-02-01T09:21:24.693 回答
2

只需#execute在迁移中使用您需要的 SQL。

execute "ALTER TABLE things MODIFY id UNSIGNED(10) NOT NULL AUTO_INCREMENT"

或者,如果该列根本不存在:

execute "ALTER TABLE things ADD COLUMN id UNSIGNED(10) NOT NULL AUTO_INCREMENT PRIMARY KEY"

那应该可以正常工作。我认为在您的迁移中,可以使用纯 SQL,并且在许多情况下这是必要的。

于 2011-07-13T08:00:46.733 回答
2

我解决了这个问题

create_table things, :id => false do |t|
  t.column :id, 'INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)'
  t.string :name
  ...

或者

create_table things, :id => false do |t|
  t.column :id, ID_COLUMN
  t.string :name
  ...

其中 ID_COLUMN 在某些配置/模块中定义并在其他迁移中使用

于 2011-07-14T09:38:39.550 回答
1

Rails 5.2 接受无符号

t.integer     :amount,          null: false, unsigned: true
于 2018-11-18T06:00:45.703 回答