ruby-on-rails - 需要在 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'
解决方案
我相信这是一个操作顺序问题。在操作员尝试创建记录之间的关系之前, FactoryBot#create
将立即将新csr
记录保存到数据库中。<<
尝试将 更改create
为build
,然后删除certificate_content_id: cc.id
。build
应该实例化,但不持久化记录。然后<<
将创建关系并保留记录。
编辑:或者,您可以保留#create
并删除<<
:
after :create do |cc|
create(:csr, signed: true, certificate_content_id: cc.id)
end
那也可以。
推荐阅读
- php - 如何在类别页面上为较新版本的 OpenCart 添加数量?
- c++ - 将类附加到 QStandardItemModel
- solidworks - 我的指挥经理浮动。如何让它回到屏幕顶部?
- debugging - SPARC 单步模式
- amazon-web-services - (Kops) Kubernetes 服务映射到 AWS Route53 中的 DNS 名称?
- gradle - 递归地在文件夹中 Gradle JAR 文件
- c# - Unity中脚本之间的最佳通信方式是什么
- javascript - 将数字与卡号进行比较
- regex - Apache 元字符
- wordpress - 分别显示每个类别