Ruby on Rails 5.2中FactoryBot父子关联外键为空如何解决?
解决FactoryBot中BusinessArea的playground_id为空问题
问题原因
你在FactoryBot里同时定义了association :parent和手动赋值playground_id {parent.id},但FactoryBot构建实例时,关联对象的创建时机与属性赋值顺序导致parent.id在赋值时还未生成(parent可能尚未保存到数据库)。同时,belongs_to :parent已经指定了foreign_key: "playground_id",FactoryBot本身会自动填充这个外键,手动赋值反而会因时机问题导致值为空。
解决方案
直接移除FactoryBot中手动设置playground_id的代码即可,FactoryBot会通过association :parent自动为你填充playground_id属性:
修改后的FactoryBot代码:
FactoryBot.define do factory :business_area do association :parent, factory: :playground name {{"en":"Test Business Area", "fr":"Business Area de test"}} code {Faker::Code.unique.rut} description {{"en":"This is a test Business Area used for unit testing"}} created_by {"Fred"} updated_by {"Fred"} status_id {0} owner_id {0} responsible_id {0} deputy_id {0} reviewer_id {0} # 移除手动赋值playground_id的代码行 end end
补充说明
如果需要确保Playground实例被保存(以生成id),可以在关联时显式指定策略,不过默认情况下FactoryBot创建关联对象时会自动保存(除非你用build方法创建business_area):
association :parent, factory: :playground, strategy: :create
内容的提问来源于stack exchange,提问作者user1185081
相关产品推荐
相关产品推荐

