当我通过与 Ruby on Rails 的has_many关联创建新记录时,如何使多态联接表的一侧唯一?



我有四种模型技能、项目、认可和个人资料。有一组技能列表需要能够随着时间的推移而扩展,所有这些都是独一无二的;我想创建一个附加到项目、认可和配置文件的联接表。

模型

class Profile < ApplicationRecord
has_many :skill_joins, as: :target
has_many :skills, through: :skill_joins
end
class Endorsement < ApplicationRecord
has_many :skill_joins, as: :target
has_many :skills, through: :skill_joins
end
class Project < ApplicationRecord
has_many :skill_joins, as: :target
has_many :skills, through: :skill_joins
end
class Skill < ApplicationRecord
belongs_to :target, polymorphic: true, optional: true
has_many :skill_joins
validates :skill_name, presence: true, uniqueness: true
end
class SkillJoin < ApplicationRecord
belongs_to :target, polymorphic: true
belongs_to :skill
end

技能加入的迁移

create_table "skill_joins", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.uuid "skill_id", null: false
t.uuid "target_id", null: false
t.string "target_type", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["target_id", "target_type"], name: "index_skill_joins_on_target_id_and_target_type"
end

我遇到了一个问题,我调用Profile.second.skills.find_or_create_by(skill_name: "something")它创建了技能和联接,但是当我调用Profile.third.skills.find_or_create_by(skill_name: "something")时,它会加载技能,但不会创建联接,而是在尝试再次创建技能时回滚。

如果我有"Javascript"、"Java"和"Ruby"的技能记录,并且我调用Profile.third.skills.find_or_create_by(skill_name: "Ruby"),我如何不创建两个"Ruby"技能,而是链接到现有的技能?

所有四种型号都使用 UUID。

你可以做Profile.third.skills << Skill.find_or_create_by(skill_name: "Ruby")。 使用导轨"魔术",当您使用铲子运算符时,它将自动创建连接记录。

最新更新