Multi-column primary keys in rails

I am trying to port a desktop application to rails (also dealing with a rather old-fashioned existing database). The problem is that I do not have a unique identifier in one column, but these are three columns of the table that guarantee the uniqueness of the record.

Given that 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.

Do I need some sort of multi-column primary key here to work with rail associations? Or am I going in the wrong direction here?

+6
source share
3 answers

Not. The primary key (for example, rails default) has a record identifier.

In addition, you can set unique keys, for example

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

This affects your database. To catch uniqueness in Rails, you need to write in your model:

  validates_uniqueness_of :email, scope: :merchant_id validates_uniqueness_of :login, scope: :merchant_id 
+11
source

There is a gem called composite_primary_keys that allows you to build a primary key using multiple columns.

So yes, you can use a multi-column primary key.

But if you can change the datamodel (which is not always the case), I would suggest adding a column identifier to each table, as this will simplify your life (and also be much more productive).

[EDIT]

Defining your class using compound_primary_keys will look like this:

 class Author set_primary_keys :author_letter, :author_nr1, :author_nr2 has_many :titles, :through => :author_title end class Title set_primary_key :title_nr end class AuthorTitle belongs_to :title, :foreign_key => :title_nr belongs_to :authori, :foreign_key => [:author_letter, :author_nr1, :author_nr2] end 

Hope this helps.

0
source

As many people have said: "If you fight Rails, it strikes back." In fact, try to avoid such situations. It’s a pain with rails if you don’t have a clean date model.

0
source

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


All Articles