【问题标题】:Creating a record using has_many :through?使用 has_many 创建记录 :through?
【发布时间】:2017-08-07 14:35:14
【问题描述】:

我有以下型号:

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

我在这里做错了什么?

【问题讨论】:

  • 您是要添加一个新的JobTitle,还是为现有的JobTitle 添加一个新的DepartmentJobTitle,还是同时添加两者?
  • 我已经创建了部门...我是。试图用Department.first 来表示它...我现在正在尝试将 JobTitle 分配给部门,我需要创建 JobTitle 或通过 DepartmentJobTitle 模型查找并分配它...。

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


【解决方案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,我希望。

【讨论】:

  • 谢谢,但是我的模型关联设置是否正确?
  • 啊,好点。我更新了。我还将根据关联名称而不是 id 进行验证:validates :department, uniqueness: { scope: :job_title },并在has_many 上添加inverse: 选项。
  • 不确定我是否遵循inverse 的建议...我应该在哪里添加它以及为什么?
  • 查看inverse: 上的 RailsGuides——它被添加到关联中以允许反向关联重新使用原始实例。
  • 不是现在,但是做个笔记看看。并且要注意任何使用引用 _id 而不是对象的代码。
猜你喜欢
  • 2011-02-20
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 2015-05-16
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
相关资源
最近更新 更多