如何创建一个 has_many 关系记录,如果关系记录已经存在于 Rails 5 中,则不会出错?

How to create a has_many relationship record which won't error if the relationship record already exists in Rails 5?

我有以下 Rails 5 个模型设置:

JobTitle
  has_many :job_title_skills
  has_many :skills, through: :job_title_skills

Skills
  has_many :job_title_skills
  has_many :job_titles, through: :job_title_skills

JobTitleSkills
  belongs_to :job_title
  belongs_to :skill
  validates :job_title_id, uniqueness: { scope: :skill_id }

我想做的是:

skill1 = Skill.find_or_create_by(title: 'YYY')

job_titles = JobTitle.all
job_titles.each_with_index do |job_title, index|
  case job_title.title
  when "XXXXX"
    job_title.skills << skill1
  end
end

我第一次 运行 以上工作正常,但是一旦记录已经在数据库中创建,上述错误 w:

ActiveRecord::RecordInvalid: Validation failed: Job title has already been taken

我如何更新上面的内容,以便 << 不是创建,而是仅在记录尚不存在时才创建?

job_title.job_title_skills.find_or_create_by(skill: skill)