How to set one more primary keys?

Now, I want to create table’s columns by “rake migrate”, but the
default primary key is only ID. how to set one more primary keys?

saying, add same table structure like this sql:

CREATE TABLE samples (
id INTEGER NOT NULL AUTO_INCREMENT
, code1 VARCHAR(3) NOT NULL
, code2 VARCHAR(2) NOT NULL
, name1 VARCHAR(20) NOT NULL
, name2 VARCHAR(20) NOT NULL
, PRIMARY KEY (id, code1, code2)
);

Thanks,

Assuming you only want a primary key for uniqueness of that column
(which would also allow you to grab that row by that primary key), you
would add

class Sample < ActiveRecord::Base

validates_uniqueness_of code1
validates_uniqueness_of code2

before_save :set_codes

def set_codes
# Insert primary key code generation script here.
end

def Sample.find_by_code_one(id)
Sample.find(:first, :conditions => [“code1 = ?”, id])
end

def Sample.find_by_code_two(id)
Sample.find(:first, :conditions => [“code2 = ?”, id])
end
end

Why would you need two primary keys?

david wrote:

Now, I want to create table’s columns by “rake migrate”, but the
default primary key is only ID. how to set one more primary keys?

saying, add same table structure like this sql:

CREATE TABLE samples (
id INTEGER NOT NULL AUTO_INCREMENT
, code1 VARCHAR(3) NOT NULL
, code2 VARCHAR(2) NOT NULL
, name1 VARCHAR(20) NOT NULL
, name2 VARCHAR(20) NOT NULL
, PRIMARY KEY (id, code1, code2)
);

Thanks,

Thanks for your help. But what I mean is how to set multiple primary
keys when table creation, maybe I’m not describe very clearly last
time. The following is sample:

class CreateSamples < ActiveRecord::Migration
def self.up
create_table :samples do |t|
t.column :code1, :string, :limit => 3, :default => “”, :null =>
false
t.column :code2, :string, :limit => 2, :default => “”, :null =>
false
t.column :name1, :string, :limit => 20, :default => “”, :null =>
false
end
end

def self.down
drop_table :t_samples
end
end

As you know, the default primary key is “ID”, but I want to set “code1”
and “code2” to primary key too. Would you have good idea?

about “why?”, because now I just try to migrate a old project to Rails.
:slight_smile:

So what you want is the ability to set the combination of the fields
to be the primary key?

In this case the above code will not help you as there can be many
equal code1/code2 values, but their combinations should be unique.
This will always be the case if ID is included in the key as it is auto
incrementing.

Try:
add_index(:samples, [:code1, :code2, :id], :unique => true)

and/or

add_index(:samples, [:code1, :code2], :unique => true)

—ABS