postgresql 在 Rails 4 迁移中设置自定义主键的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19050978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problems setting a custom primary key in a Rails 4 migration
提问by Alexander
I use postgresql 9.3, Ruby 2.0, Rails 4.0.0.
我使用 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:
在阅读了有关在表上设置主键的 SO 的大量问题后,我生成并添加了以下迁移:
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
I also added self.primary_key = "uid"
to my model.
我也添加self.primary_key = "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?
迁移成功运行,但是当我使用 pgAdmin III 连接到数据库时,我看到 uid 列未设置为主键。我错过了什么?
回答by peresleguine
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.
看看这个答案。尽量execute "ALTER TABLE shareholders ADD PRIMARY KEY (uid);"
不要在 create_table 块中指定 primary_key 参数。
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:There is natural way (found here), but only with int4 type:
UPD:有很自然的方式(在这里找到),但仅限于 int4 类型:
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
回答by kairya1975
In my environment(activerecord 3.2.19 and postgres 9.3.1),
在我的环境中(activerecord 3.2.19 和 postgres 9.3.1),
:id => true, :primary_key => "columname"
creates a primary key successfully but instead of specifying ":limit => 8" the column' type is int4!
成功创建了一个主键,但不是指定 ":limit => 8" 列的类型是 int4!
create_table :m_check_pattern, :primary_key => "checkpatternid" do |t|
t.integer :checkpatternid, :limit => 8, :null => false
end
Sorry for the incomplete info.
抱歉信息不完整。
回答by NAVPREET SINGH
I have created migrations like this:
我创建了这样的迁移:
class CreateShareholders < ActiveRecord::Migration
def change
create_table :shareholders, id: false do |t|
t.integer :uid, primary_key: true
t.string :name
t.integer :shares
t.timestamps
end
end
end