且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Rails 4迁移中设置自定义主键时出现问题

更新时间:2023-11-24 12:52:16

看看这个答案。尝试执行 ALTER TABLE股东添加主键(uid); 而不在create_table块中指定primary_key参数。

Take a look at this answer. Try to execute "ALTER TABLE shareholders ADD PRIMARY KEY (uid);" without specifying primary_key parameter in create_table block.

我建议这样编写迁移文件(以便您可以正常回滚):

I suggest to write your migration like this (so you could rollback normally):

class CreateShareholders < ActiveRecord::Migration
  def up
    create_table :shareholders, id: false do |t|
      t.integer :uid, limit: 8
      t.string :name
      t.integer :shares

      t.timestamps
    end
    execute "ALTER TABLE shareholders ADD PRIMARY KEY (uid);"
  end

  def down
    drop_table :shareholders
  end
end

UPD:有一种自然的方法(在此处找到),但仅使用int4类型:

UPD: There is natural way (found here), but only with int4 type:

class CreateShareholders < ActiveRecord::Migration
  def change
    create_table :shareholders, id: false do |t|
      t.primary_key :uid
      t.string :name
      t.integer :shares

      t.timestamps
    end    
  end
end