Given a Rails 5 has_and_belongs_to_many, how to create a join record?

时间:2017-08-04 13:04:41

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

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?

1 个答案:

答案 0 :(得分:2)

试试这个:

align-items: flex-start