2017-11-11 238 views
0

我有4個車型,這是CompanyCandidateJobApplication的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 

我不知道CandidateJobsApplication之間的關係是否正確。如果有人能提出一些改進建議,那將是很棒的。謝謝。

回答

1

你在正確的軌道上。添加間接關聯設定以及會讓你查詢向上和向下的層次結構:

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 
+0

另外一個提示是將你的例子寫成代碼或元代碼。我從來沒有寫過類名和內容,因爲如果它正確縮進,它更容易遵循。 – max

0

我認爲建立主動記錄關聯的最簡單方法是想象你現實生活中的關聯。在這種情況下,一個公司有幾個工作,每個工作有幾個應用程序,每個應用程序有一個候選人。

因此,關係是

爲公司

has_many :jobs 

的工作

belongs_to :company 
has_many :applications 

的應用

belongs_to :job 
has_one :candidate 

的候選人

belongs_to :application 
+1

我會把應用'belongs_to的:canditate'因爲這將讓候選人申請多個職位。這意味着OP實際上做對了。 – max

+0

我會通過::jobs'和'has_many:candidates,通過:: applications'添加Comapny'has_many:applications, –