Problems Configuring a Custom Primary Key in Rails 4 Migration

I am using postgresql 9.3, Ruby 2.0, Rails 4.0.0.

After reading numerous questions about SO regarding setting the primary key in the 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 is successful, but when I connect to the database using pgAdmin III, I see that the uid column is not set as the primary key. What am I missing?

+6
source share
3 answers

Check out this answer . Try execute "ALTER TABLE shareholders ADD PRIMARY KEY (uid);" without specifying the primary_key parameter in the create_table block.

I suggest writing your migration as follows (so you can roll back 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 a natural way ( found here ), but only with type 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 
+17
source

In my environment (activerecord 3.2.19 and postgres 9.3.1),

 :id => true, :primary_key => "columname" 

creates the 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 information.

0
source

I created the migrations as follows:

 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 
0
source

Source: https://habr.com/ru/post/954777/


All Articles