2

I have the following schema:

class Industry << ApplicationRecord
  has_and_belongs_to_many :departments
end

# Relationship table: departments_industries

class Department << ApplicationRecord
  has_and_belongs_to_many :industries
  has_and_belongs_to_many :job_titles
end

# Relationship table: departments_job_titles

class JobTitle << ApplicationRecord
  has_and_belongs_to_many :departments
end

When I want to create a relationship record:

department.job_titles.find_or_create_by(title: title)

The above DOES end up creating a record in departments_job_titles ONLY if the query above create's the record... If the JobTitle already exists, Rails is NOT creating the relationship record in departments_job_titles.

How can I update:

department.job_titles.find_or_create_by(title: title)

To always create the relationship record in departments_job_titles when either the JobTitle record is found or created?

halfer
  • 19,824
  • 17
  • 99
  • 186
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • 2
    In Rails style guide (https://github.com/bbatsov/rails-style-guide#activerecord ctrl+F "has_and_belongs_to_many") it is recommended to use `has_many :things, through: :join_records` instead of HABTM, as it (quoting) *"allows additional attributes and validations on the join model"* (like `favorite`, `position` attributes, etc) – MrYoshiji Aug 04 '17 at 14:21

1 Answers1

3

Try this:

department.job_titles << JobTitle.find_or_create_by(title: title)
romainsalles
  • 2,051
  • 14
  • 17