How to implement composite primary keys in rails

I have a model Userthat looks like this:

class User < ApplicationRecord
  belongs_to :organization
  belongs_to :department
end

The table usersin the database has two foreign keys organization_idand department_id. How can I make these two columns a composite primary key? So far I have seen two approaches:

Option 1

Use composite_primary_keysgem

Option 2

Add an index to each of the two columns using something like this:

add_index :users, [:organization_id, :department_id], unique: true

My question

What is the best way to uniquely identify rows in a table users, where the line should be department_idand organization_idto uniquely identify? What is the difference between indexing both columns and just turning each column into the primary key of the table?

Thank!

+4
1

.

, id .

... , , , , , t... BTW, , , Rails... , - . - , id , . . , , ...

, id , , organisation_id + department_id...

. , / - , , ... , .:) ... , Rails , , ... PITA, .

... - . , org_id/dept_id ... , ... db, ...

(OTOH) , ... , - , 42 23 . , , db.

+6

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


All Articles