Rails迁移:带有unsigned int的主键id(10)

时间:2011-07-13 05:33:40

标签: ruby-on-rails rails-migrations

我想通过rails migration

在我的表中定义主键ID,如下所示

id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT

我正在使用mysql db。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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,在许多情况下这是必要的。

答案 2 :(得分:2)

我用这个

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

OR

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

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

答案 3 :(得分:0)

Rails 5.2确实接受未签名的

t.integer     :amount,          null: false, unsigned: true