需要在工厂中指定 id 以进行关联

Required to specify id in factory for association

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

工厂

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

certificate_content 型号

has_many :csrs, dependent: :destroy

企业社会责任模型

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

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

尝试将 create 更改为 build,并删除 certificate_content_id: cc.idbuild 应该实例化记录,而不是持久化记录。然后 << 将创建关系并保存记录。

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

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

那也行。