24
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで複合キーを扱う(composite_primary_keys)

Posted at

composite_primary_keysを利用する事で複合キーを扱えます。

参考:
Railsで規約に沿わない古いデータを扱う
rails 既存DBを使ってrailsしてみた。

インストール

#Gemfile
gem 'composite_primary_keys'

モデル

class Company < ActiveRecord::Base
  self.primary_key = :company_id
  has_many :company_employes, foreign_key: :company_id
  # foreignキーも複合キーにする場合は、
  # has_many :company_employes, foreign_key: [:company_id, :employ_id]と配列で定義する
end
class Employ < ActiveRecord::Base
  self.primary_key = :employ_id
end
class CompanyEmploy < ActiveRecord::Base
 #ここで複合キーを利用する
 self.primary_keys = :company_id, :employ_id
end

利用例

# 複合キーをfindする例

company = Company.find(1)

# keyに[company_id, employ_id]を指定.
company.company_employes.find([1,35]) 
# SELECT * FROM CompanyEmploy WHERE CompanyEmploy.company_id = 1 AND CompanyEmploy.company_id AND CompanyEmploy.employ_id

company.company_employes.find(1) # NG
# 複合キーをwhereする例

company = Company.find(1)

# foregin_keyに指定しているcompany_idは、自動的にwhere句に含まれる.
company.company_employes.where("employ_id = ?", 35) 
# SELECT * FROM CompanyEmploy WHERE CompanyEmploy.company_id = 1 AND CompanyEmploy.employ_id
24
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?