首页 > 解决方案 > 需要在 factory 中指定 id 以进行关联

问题描述

我有一个在创建后创建关联的工厂。除非我指定外键,否则我不会工作。即使在模型中指定了外键。这是正常的吗?如果不是,我该如何解决?

工厂

trait :with_csr do
  after :create do |cc|
    cc.csrs << create(:csr, signed: true, certificate_content_id: cc.id)
  end
end

证书内容模型

has_many :csrs, dependent: :destroy

企业社会责任模型

belongs_to  :certificate_content, touch: true, foreign_key: 'certificate_content_id'

标签: ruby-on-railsactiverecordfactory-bot

解决方案


我相信这是一个操作顺序问题。在操作员尝试创建记录之间的关系之前, FactoryBot#create将立即将新csr记录保存到数据库中。<<

尝试将 更改createbuild,然后删除certificate_content_id: cc.idbuild应该实例化,但不持久化记录。然后<<将创建关系并保留记录。

编辑:或者,您可以保留#create并删除<<

after :create do |cc|
  create(:csr, signed: true, certificate_content_id: cc.id)
end

那也可以。


推荐阅读