Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a unique primary key based on 2 columns

I would like to define a unique key for records based on 2 columns : 'id' and 'language'

to let the user submits the following strings : id=1 language=en value=blabla english id=1 language=fr value=blabla french

I tried to use set_primary_key and also add_index but it didn't work ( add_index :words, ["id", "language_id"], :unique => true )

I have the following model :

class Word < ActiveRecord::Base   belongs_to :dictionnary   belongs_to :language    attr_accessible :lang, :rev, :value, :dictionnary_id, :language_id    validates :value, :uniqueness => true  end   

and this

class Language < ActiveRecord::Base     has_many :words      attr_accessible :lang end 
like image 731
Stéphane V Avatar asked Oct 05 '12 12:10

Stéphane V


People also ask

Can I have 2 columns as primary key?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

What is unique primary key?

Primary Key is a column that is used to uniquely identify each tuple of the table. It is used to add integrity constraints to the table. Only one primary key is allowed to be used in a table. Duplicate and NULL (empty) values are not valid in the case of the primary key.

How do I make two columns unique in MySQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.


1 Answers

add_index :words, ["id", "language_id"], :unique => true

It should work. Maybe you have already some non-unique data in your db and index can't be created? But (as @Doon noticed it will be redundant since id is always unique). So you need create primary key on two columns.

To define 2 column primary key in rails use:

create_table :words, {:id => false} do |t|   t.integer :id   t.integer :language_id   t.string :value   t.timestamps end execute "ALTER TABLE words ADD PRIMARY KEY (id,language_id);" 

And set primary_key in your model with this gem: http://rubygems.org/gems/composite_primary_keys:

class Word < ActiveRecord::Base     self.primary_keys = :id,:language_id end 
like image 154
rogal111 Avatar answered Nov 11 '22 22:11

rogal111