Search code examples
ruby-on-railsactiverecordruby-on-rails-5activemodel

Creating a record using has_many :through?


I have the following models:

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

This is erring 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 has the following fields: id, department_id, job_title_id

What am I doing wrong here?


Solution

  • Try this:

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

    Or that second line could be:

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

    Also:

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

    ... and ...

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

    ... and think about what behaviour you want if someone destroys a JobTitle or Department -- either you want the DepartmentJobTitle destroyed also, or you want the destroy to be prevented, I expect.