Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associated object does not have a primary key

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
like image 387
belgoros Avatar asked Apr 24 '17 14:04

belgoros


2 Answers

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.

like image 154
Jeremy Evans Avatar answered Oct 13 '22 15:10

Jeremy Evans


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
like image 28
kranzky Avatar answered Oct 13 '22 15:10

kranzky