Rails 令人困惑的联想

Rails associations confusing

我有4个模型,分别是CompanyCandidateJobApplication

对于Company

has_many :candidates
has_many :jobs

对于Candidate

belongs_to :company
has_one :application

对于Jobs

belongs_to :company
has_many :applications

对于Application

belongs_to :candidate
belongs_to :job

我不确定CandidateJobsApplication之间的关系是否正确。如果有人可以提出一些改进建议,那就太好了。谢谢。

我认为建立 activerecord 关联的最简单方法是想象您在现实生活中的关联。在此案例中,一家公司有多个职位,每个职位有多个申请,每个申请有一个候选人。

因此关系将是

公司

has_many :jobs

求职

belongs_to :company
has_many :applications

申请

belongs_to :job
has_one :candidate

候选人

belongs_to :application

你走在正确的轨道上。添加间接关联也将允许您在层次结构中向上和向下查询:

class Company < ApplicationRecord
  has_many :jobs
  has_many :applications, through: :jobs
  has_many :candidates, through: :applications
end

class Job < ApplicationRecord
  belongs_to :company
  has_many :applications
  has_many :candidates, through: :applications
end

class Application  < ApplicationRecord
  belongs_to :candidate
  belongs_to :job
  has_one :company, through: :job
end

class Candidate < ApplicationRecord
  has_many :applications
  has_many :jobs, through: :applications
  has_many :companies, through: :jobs
end