Associated object does not have a primary key
Asked Answered
C

2

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
Cetacean answered 24/4, 2017 at 14:4 Comment(0)
D
6

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.

Dharana answered 24/4, 2017 at 15:37 Comment(0)
D
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
Delphadelphi answered 19/6, 2019 at 8:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.