使用FactoryGirl时association_id为nil的问题求助
association_id Nil Issue with FactoryGirl Let's break down what's going wrong here and get your associations working correctly.
The Core Problem
You're passing foreign key field names (entity_id, social_media_site_id) to the association method, but FactoryGirl expects the association name defined in your model instead. When you use the field name directly, FactoryGirl can't properly create the associated record and populate the foreign key—hence the nil values.
Step 1: Confirm Your Model Associations
First, let's clarify what your AccountInfo model's association looks like, since you mentioned it "belongs to Person" and have an entity_type field (this hints at either a custom foreign key or a polymorphic association):
Scenario 1: Custom Foreign Key (Non-Polymorphic)
If your model uses a custom foreign key for the Person association:
# app/models/account_info.rb class AccountInfo < ApplicationRecord belongs_to :person, foreign_key: :entity_id belongs_to :social_media_site, foreign_key: :social_media_site_id end
Scenario 2: Polymorphic Association
If entity is a polymorphic association (since you have entity_type):
# app/models/account_info.rb class AccountInfo < ApplicationRecord belongs_to :entity, polymorphic: true belongs_to :social_media_site end
Step 2: Fix the Factory Definition
Adjust your factory to use the correct association names instead of the foreign key fields:
For Scenario 1 (Custom Foreign Key):
FactoryGirl.define do factory :account_info do entity_type 1 # Keep this if it's a required field for your logic account_key { Faker::Twitter.user[:id] } # Use the association name :person, FactoryGirl auto-sets entity_id association :person, factory: :person # Use :social_media_site instead of social_media_site_id association :social_media_site, factory: :twitter end end
For Scenario 2 (Polymorphic Association):
FactoryGirl.define do factory :account_info do # FactoryGirl will auto-set entity_type when you associate :entity with a Person # entity_type 'Person' # Uncomment if you need to hardcode it instead of auto-set account_key { Faker::Twitter.user[:id] } # Associate the polymorphic :entity with the :person factory association :entity, factory: :person association :social_media_site, factory: :twitter end end
Why This Works
When you pass the association name (like :person or :entity) to association, FactoryGirl:
- Creates an instance of the associated model using the specified factory
- Automatically assigns the correct foreign key (e.g.,
entity_idfor the:personassociation) on yourAccountInforecord
Bonus: Overriding Associated Attributes
If you need to customize the associated record's attributes, you can use a block:
association :entity, factory: :person do first_name "Lucian" last_name "Tarna" end
内容的提问来源于stack exchange,提问作者Lucian Tarna

