5

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_manyin 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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
belgoros
  • 3,590
  • 7
  • 38
  • 76

2 Answers2

5

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.

Jeremy Evans
  • 11,959
  • 27
  • 26
1

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
kranzky
  • 1,328
  • 11
  • 16