Reputation: 69
I have 4 models, which are Company
, Candidate
, Job
and Application
For Company
has_many :candidates
has_many :jobs
For Candidate
belongs_to :company
has_one :application
For Jobs
belongs_to :company
has_many :applications
For Application
belongs_to :candidate
belongs_to :job
I'm not sure whether the relationships between Candidate
, Jobs
and Application
are correct or not. It would be great if someone can give some suggestions for improvement. Thank you.
Upvotes: 0
Views: 94
Reputation: 101831
You're on the right track. Adding indirect assocations as well will let you query up and down the heirarchy:
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
Upvotes: 1
Reputation: 1
I think the easiest way to build activerecord associations is to imagine your associations in real life. In this case, a company has several jobs, each job has several applications, and each application has one candidate.
Hence the relation would be
for Company
has_many :jobs
for Job
belongs_to :company
has_many :applications
for Application
belongs_to :job
has_one :candidate
for Candidate
belongs_to :application
Upvotes: 0