Reputation: 110960
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?
Upvotes: 2
Views: 1426
Reputation: 2143
Try this:
department.job_titles << JobTitle.find_or_create_by(title: title)
Upvotes: 3