I still can't find a solution to fix an association factory issue when using Sequel.
I have two models relying on one_to_many
, which is the same as has_many
in Active Record, and many_to_one
, which is the same as belongs_to
in Active Record.
Here are the defined factories:
FactoryGirl.define do
to_create { |instance| instance.save }
factory :post do
title "some title"
end
end
FactoryGirl.define do
to_create { |instance| instance.save }
factory :comment do
content "some content"
association :post, strategy: :build
end
end
When running build(:comment)
, it fails with:
Associated object does not have a primary key.
Does anyone have an idea how to fix that? I can always build/create a post first, then sign it to a comment, but it is tedious. More than that, I'll have to remove association :post, strategy: :build
and use some Integer random value.
I'm using:
factory_girl_rails 4.8.0
ruby 2.4.0
sequel-rails 0.9.15
sequel 4.45.0
Sequel doesn't supporting adding an associated object to a unsaved object, unless you are using the nested_attributes plugin to create both at the same time. So unless FactoryGirl has specific code to deal with that, it probably will not work.
Looks like your strategy should be create, not build. Here's how I solved it with FactoryBot:
after(:build) { |comment| comment.post ||= create(:post) }
This will happen by default if you specify the association without any parameters and use this configuration:
FactoryBot.use_parent_strategy = false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With