![](/img/trans.png)
[英]Best way to specify a default record for a has_many relationship in rails
[英]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
上面的代碼在我第一次運行時運行良好,但是一旦在數據庫中創建了記錄,上面的錯誤就會出現:
ActiveRecord::RecordInvalid: Validation failed: Job title has already been taken
我如何更新以上內容,以便在記錄不存在的情況下僅創建<< <<,而不是創建?
job_title.job_title_skills.find_or_create_by(skill: skill)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.