0

当我在控制台中使用 pry 进行调试时,我运行了brief = Factory(:brief,:project => Factory(:project)) 这个命令。它应该可以工作,但我得到了这个错误。

 ActiveRecord::RecordNotUnique: PG::Error: ERROR:  duplicate key value violates unique constraint "index_briefs_on_project_id"
    DETAIL:  Key (project_id)=(15389) already exists.
    : INSERT INTO "briefs" ("project_id", "duration", "brand_name", "brand_info", 
"customer_info", "competitor_info", "desired_impression", "competencies", "preferences",
 "examples", "notes", "created_at", "updated_at", "channel_id") VALUES (15389, 14, NULL, 
'brand info', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
'2013-04-06 01:07:04.717364', '2013-04-06 01:07:04.717364', NULL) RETURNING "id"

为什么会发生此错误,我该如何解决?

编辑:我添加了我的工厂文件

Brief_factory.rb

Factory.define :brief, :class => Brief do |b|
  b.brand_info 'brand info'
  b.duration 14
end

project_factory.rb

Factory.define :project, :class => Project do |p|
  p.association :owner, :factory => :customer

  p.title 'project title'
  p.description 'project description'
  p.stage :brief_completed
  p.contest_type :standard

  p.brief Factory.build(:brief)
  p.association :project_type, :factory => :project_type
end
4

1 回答 1

2

看起来project工厂正在自动创建brief. 因此Factory(:brief,:project => Factory(:project))将尝试创建与同一项目相关联的两个简报。第二个失败,因为您对表project_id中的列有唯一约束briefs

使用您定义的工厂,您可能可以做您在 Pry 中尝试做的事情:

project = Factory(:project)
brief = project.brief

要不就:

brief = Factory(:project).brief
于 2013-04-06T14:17:02.313 回答