Define a unique primary key based on 2 columns

后端 未结 7 585
长情又很酷
长情又很酷 2021-01-31 02:52

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=bl

7条回答
  •  不思量自难忘°
    2021-01-31 03:18

    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
    

提交回复
热议问题