5
8

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> 中間テーブルのカラム名がモデル名と違う場合

Posted at

##構成
Memberテーブル
Registrantテーブル

この二つを繋げるための、
中間テーブル Recruitmentテーブル


Recruitmentテーブルのカラム
recruiter_id(モデル名と違う)
registrant_id(モデル名と同じ)

app/model/member.rb

class Member < ActiveRecord::Base
  has_many :recruitments, class_name: "Recruitment", foreign_key: "recruiter_id"
  has_many :registrants, through: :recruitments
end

app/model/registrant.rb

class Registrant < ActiveRecord::Base
  has_many :recruitments
  has_many :recruiters, through: :recruitments
end

app/model/recruitment.rb

class Recruitment < ActiveRecord::Base
  belongs_to :recruiter, class_name: "Member", foreign_key: "recruiter_id"
  belongs_to :registrant
end

migration

  t.references :recruiter, null: false
  t.references :registrant, null: false

add_index :recruitments, [ :recruiter_id, :registrant_id ], unique: true
add_foreign_key :recruitments, :members, column: "recruiter_id"
add_foreign_key :recruitments, :registrants
5
8
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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?