2017-08-07 90 views
0

我有以下型號:使用has_many創建記錄:通過?

class Department < ApplicationRecord 
    has_many :department_job_titles 
    has_many :job_titles, through: :department_job_titles 
end 

class JobTitle < ApplicationRecord 
    has_and_belongs_to_many :departments 
end 

class DepartmentJobTitle < ApplicationRecord 
    belongs_to :department 
    belongs_to :job_title 
    validates :department_id, uniqueness: { scope: :job_title_id } 
end 

這是犯錯誤的W¯¯PG::UndefinedColumn: ERROR: column department_job_titles.title does not exist LINE 1: ... "department_job_titles"."department_id" = $1 AND "departmen...

Department.first.department_job_titles.find_or_create_by(title: title) 

DepartmentJobTitle具有以下字段:id, department_id, job_title_id

什麼我錯在這裏做什麼?由於

+1

你想添加一個新的'JobTitle',爲現有的'JobTitle'添加一個新的'DepartmentJobTitle',或者同時添加嗎? –

+0

我已經創建了部門...我是。試圖用'Department.first'來表示...我現在試圖給部門分配一個JobTitle,並且我需要創建JobTitle或者通過DepartmentJobTitle模型找到並分配它.... – AnApprentice

回答

1

試試這個:

job_title = JobTitle.find_or_create_by(title: title) 
Department.first.job_titles << job_title unless job_title.in? Department.first.job_titles 

或者說,第二行可能是:

另外:

class JobTitle < ApplicationRecord 
    has_many :department_job_titles 
    has_many :departments, through: :department_job_titles 
end 

......還有......

class DepartmentJobTitle < ApplicationRecord 
    belongs_to :department 
    belongs_to :job_title 
    validates :department, presence: true, uniqueness: { scope: :job_title } 
    validates :job_title, presence: true 
end 

...並考慮你想要什麼樣的行爲,如果有人摧毀了JobTitleDepartment - 要麼也要銷燬DepartmentJobTitle,要麼防止destroy被阻止。

+0

謝謝,但我有正確的模型關聯設置? – AnApprentice

+1

啊好點。我更新了。我還會根據關聯名稱進行驗證,而不是根據id:'validates:department,uniqueness:{scope::job_title}',並在'has_many'上添加'inverse:'選項。 –

+0

不確定我是否正在遵循'反向'建議......我會在哪裏添加該內容?爲什麼? – AnApprentice

相關問題