在Rails 4迁移中设置自定义主键时出现问题 [英] Problems setting a custom primary key in a Rails 4 migration

查看:103
本文介绍了在Rails 4迁移中设置自定义主键时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PostgreSQL 9.3,Ruby 2.0,Rails 4.0.0。

I use postgresql 9.3, Ruby 2.0, Rails 4.0.0.

在阅读了关于在表上设置主键的大量问题之后,我生成并添加了以下迁移:

After reading numerous questions on SO regarding setting the Primary key on a table, I generated and added the following migration:

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

      t.timestamps
    end
  end
end

我还添加了 self.primary_key = uid。

I also added self.primary_key = "uid" to my model.

迁移成功运行,但是当我使用pgAdmin III连接到数据库时,我看到uid列是未设置为主键。我缺少什么?

The migration runs successfully, but when I connect to the DB using pgAdmin III I see that the uid column is not set as primary key. What am I missing?

推荐答案

看看这个答案。尝试执行 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

这篇关于在Rails 4迁移中设置自定义主键时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆