Lucian Tarna
Lucian Tarna

Reputation: 1827

FactoryGirl association_id is nil

I am trying to use factory_girl with associations. I have 2 models: account_info and person. AccountInfo belongs to a persons o my account_info factory looks like:

FactoryGirl.define do
  factory :account_info do
    entity_type 1
    account_key { Faker::Twitter.user[:id] }
    association :entity_id, factory: [:person]
    association :social_media_site_id, factory: [:twitter]
  end
end

Per documentation:

You can also specify a different factory or override attributes:

factory :post do
  # ...
  association :author, factory: :user, last_name: "Writely"
end
The behavior of the association method varies depending on the build strategy used for the parent object.

# Builds and saves a User and a Post
post = create(:post)
post.new_record?        # => false
post.author.new_record? # => false

# Builds and saves a User, and then builds but does not save a Post
post = build(:post)
post.new_record?        # => true
post.author.new_record? # => false

It creates the record Person but the AccountInfo entity_id remains nil. Why?

d = FactoryGirl.create(:account_info)
d.reload
  AccountInfo Load (0.5ms)  SELECT  "account_infos".* FROM "account_infos" WHERE "account_infos"."id" = $1 LIMIT $2  [["id", 443], ["LIMIT", 1]]
 => #<AccountInfo id: 443, entity_type: "legislator", account_key: "498133264559673104", social_media_site_id: nil, entity_id: nil, created_at: "2018-04-29 13:18:49", updated_at: "2018-04-29 13:18:49"> 

Versions:

factory_girl_rails (4.9.0)
rails (5.1.6)
ruby (2.5.0)

Upvotes: 0

Views: 361

Answers (1)

Taryn East
Taryn East

Reputation: 27747

It's odd that entity= is not defined. Do you have the association defined on your AccountInfo model? (eg belongs_to :entity)? If so, that could be the problem (or something similar).

Upvotes: 2

Related Questions