Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multicolumn primary keys in rails

I'm trying to migrate a desktop application to rails (also dealing with quite old fashioned existing database). The problem is that I don't have a unique ID in one column, but it's three columns of a table that guarantee uniqueness of a record.

Given I have three tables:

authors
  author_name,
  author_letter,
  author_nr1,
  author_nr2
  ...

titles
  titel_nr,
  titel_name,
  ...

author_titles
  titel_nr,
  author_letter,
  author_nr1,
  author_nr2

The "primary key" of authors consists of author_letter, author_nr1, author_nr2 here.

So do I need sort of a multicolumn primary key here to have rails associations working? Or am I going in the wrong direction here?

like image 605
blissini Avatar asked Nov 20 '11 12:11

blissini


1 Answers

No. The Primary Key is (like rails default) the ID of the Record.

In addition you can set unique Keys like

    add_index :users, [:merchant_id, :email], unique: true
    add_index :users, [:merchant_id, :login], unique: true

This potects your database. To catch the uniqueness in Rails you need to write into your model:

  validates_uniqueness_of :email,    scope: :merchant_id
  validates_uniqueness_of :login,    scope: :merchant_id
like image 89
Tim Kretschmer Avatar answered Sep 25 '22 01:09

Tim Kretschmer