的Rails协会混淆
我有4个车型,这是Company
,Candidate
,Job
和Application
的Rails协会混淆
对于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
我不知道Candidate
,Jobs
和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
我认为建立主动记录关联的最简单方法是想象你现实生活中的关联。在这种情况下,一个公司有几个工作,每个工作有几个应用程序,每个应用程序有一个候选人。
因此,关系是
为公司
has_many :jobs
的工作
belongs_to :company
has_many :applications
的应用
belongs_to :job
has_one :candidate
的候选人
belongs_to :application
我会把应用'belongs_to的:canditate'因为这将让候选人申请多个职位。这意味着OP实际上做对了。 – max
我会通过::jobs'和'has_many:candidates,通过:: applications'添加Comapny'has_many:applications, –
另外一个提示是将你的例子写成代码或元代码。我从来没有写过类名和内容,因为如果它正确缩进,它更容易遵循。 – max