multicolumn primary keys in rails

2020-06-19 10:22发布

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?

3条回答
迷人小祖宗
2楼-- · 2020-06-19 10:28

As many people said: "if you fight Rails, it'll strike back". Really try to avoid such situations, It's pain with rails, if you don't have a clean datamodel.

查看更多
SAY GOODBYE
3楼-- · 2020-06-19 10:38

There exists a gem called composite_primary_keys that will allow to build a primary key using multiple columns.

So, yes, you can use multicolumn primary key.

But, if you are able to change the datamodel (which is not always the case), I would propose to add a column ID to each table, as this will make your life easier (and is also much more performant).

[EDIT]

Your class definition with composite_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.

查看更多
姐就是有狂的资本
4楼-- · 2020-06-19 10:41

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
查看更多
登录 后发表回答