[英]How do I make one side of a polymorphic join table unique when I create new records through a has_many association with Ruby on Rails?
我有四个模型技能、项目、背书和简介。 有一系列技能需要随着时间的推移而扩展,所有技能都是独一无二的; 我想创建一个附加到 Project、Endorsement 和 Profile 的连接表。
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")
。 使用 rails “magic”,当您使用 shovel 运算符时,它会自动创建连接记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.