multicolumn primary keys in rails

孤街醉人 提交于 2019-12-03 14:38:34

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!