2
我有以下模式:鑑於Rails 5 has_and_belongs_to_many,如何創建連接記錄?
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
當我想創建一個關係記錄:
department.job_titles.find_or_create_by(title: title)
上面並最終在departments_job_titles
創建記錄只有當上面的查詢創造的紀錄。 ..如果JobTitle已經存在,Rails不會在departments_job_titles
中創建關係記錄。
如何更新:
department.job_titles.find_or_create_by(title: title)
要時,無論是JOBTITLE記錄被發現或創造總是創建departments_job_titles
的關係記錄?
感謝
在Rails風格指南(https://github.com/bbatsov/rails-style-guide#activerecord CTRL + F 「has_and_belongs_to_many」)建議使用'has_many:things,通過::join_records'而不是HABTM,因爲它(引用)*「允許在連接模型上附加屬性和驗證」*(如'favorite','position'屬性等) – MrYoshiji