gpt4 book ai didi

ruby-on-rails - 更改模型的主键属性时,Rails FactoryGirl 重复键值违反唯一约束

转载 作者:行者123 更新时间:2023-12-02 03:55:55 25 4
gpt4 key购买 nike

你知道我在这个测试中做错了什么吗?

require "rails_helper"

describe "Rep", type: :feature do
scenario "has a Manager and a Region" do
rep = FactoryGirl.create(:rep)
expect(rep.boss.email).to eq("first.last@email.com")
expect(rep.region.name).to eq("NAT")
end
end

给定区域的此类

class Region < ApplicationRecord
self.primary_key = "lid"
has_many :reps
end

我已更改区域的主键以引用列lid

FactoryGirl.define do
factory :rep do
lid 1
email '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="593f302b2a2d7735382a2d193c34383035773a3634" rel="noreferrer noopener nofollow">[email protected]</a>'
association :boss, strategy: :build
association :region, factory: :region, strategy: :build
end

factory :boss, class: Rep do
lid 2
email '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e3c2b3e60232f202f292b3c0e2b232f2722602d2123" rel="noreferrer noopener nofollow">[email protected]</a>'
manager true
association :region, factory: :region, strategy: :build
end
end

现在,当构建工厂中的关联区域时,它会导致对该区域进行唯一性验证。

我使用这些来自另一个系统的称为旧版 ID (lid) 的 ID,并将它们用作主键(数据库迁移已设置为可以处理它们)。

我可以构建此应用程序特有的其他关联,因此具有标准的“id”字段

FactoryGirl.define do
factory :region do
lid 10
name 'NAT'
end
end

我想要的只是代表老板都属于同一个地区,所以当我建立一个代表时 工厂它带有 bossregion 关联。

希望这只是一些我没有考虑的愚蠢的事情:confused:

rspec spec spec/features/reps/have_managers.rb
F

Failures:

1) Reps belong to a manager
Failure/Error: rep = FactoryGirl.create(:rep)

ActiveRecord::RecordNotUnique:
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_regions_on_lid"
DETAIL: Key (lid)=(10) already exists.
: INSERT INTO "regions" ("lid", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "lid"
# ./spec/features/reps/have_managers.rb:6:in `block (2 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# PG::UniqueViolation:
# ERROR: duplicate key value violates unique constraint "index_regions_on_lid"
# DETAIL: Key (lid)=(10) already exists.
# ./spec/features/reps/have_managers.rb:6:in `block (2 levels) in <top (required)>'

到目前为止,我已经关闭了 region_id null false flag 并将 belongs_to 设为可选,这样我就可以注释掉区域关联并忽略它现在

最佳答案

我确信您已经弄清楚了这一点,但为了覆盖这一点,您的工厂中发生了一些重叠的事情。由于老板是代表,因此您不希望将老板工厂与代表工厂关联起来,否则您最终会得到任何重叠的重复条目。相反,您可以考虑使用特征:

FactoryGirl.define do
factory :rep, class: Rep do
sequence(:lid) { |n| n }
sequence(:email) { |e| "first.last#{e}@email.com" }
association :region, factory: :region

trait :boss do
manager true
end
end
end

然后,当您想要创建/构建这些时,您可以使用如下内容:

let(:rep) { create(:rep) }
let(:boss) { create(:rep, traits: [:boss]) }

关于ruby-on-rails - 更改模型的主键属性时,Rails FactoryGirl 重复键值违反唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com