Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

ruby - Problems setting a custom primary key in a Rails 4 migration

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...