2017-08-07 95 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

相关问题