我有四个模型:技能,项目,认可和个人资料。有一系列技能需要随着时间的推移而扩展,这些都是唯一的。我想创建一个连接表,该表连接到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”时,当您使用铲子运算符时,它将自动创建联接记录。