Problems setting a custom primary key in a Rails 4 migration

独自空忆成欢 提交于 2019-11-27 03:34:44

问题


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?


回答1:


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



回答2:


In my environment(activerecord 3.2.19 and 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!

create_table :m_check_pattern, :primary_key => "checkpatternid" do |t|
  t.integer     :checkpatternid, :limit => 8, :null => false
end

Sorry for the incomplete info.




回答3:


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


来源:https://stackoverflow.com/questions/19050978/problems-setting-a-custom-primary-key-in-a-rails-4-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!