使用has_many:through创建记录?

时间:2017-08-07 14:35:14

标签: ruby-on-rails activerecord ruby-on-rails-5 activemodel

我有以下型号:

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" = $1 AND "departmen...

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

DepartmentJobTitle包含以下字段:id, department_id, job_title_id

我在这里做错了什么?感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

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