使用 has_many 创建记录 :through?

Creating a record using has_many :through?

我有以下型号:

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

这是错误的 PG::UndefinedColumn: ERROR: column department_job_titles.title does not exist LINE 1: ... "department_job_titles"."department_id" = AND "departmen...

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

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

我在这里做错了什么?

试试这个:

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

或者第二行可以是:

Department.first.job_titles = (Department.first.job_titles + [job_title]).uniq

还有:

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被阻止,我希望。