Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle foreign key assoication in FactoryGirl

I have two models joined through a foreign_key attribute which they both share.

# app/models/building.rb
belongs_to :building_basic_info, primary_key: "name", foreign_key:"name"

# app/models/building_basic_info.rb
has_many :buildings, primary_key: "name", foreign_key:"name"

I'm trying to write a Factory that will create both a building and a building_basic_info and associate them through the attribute name.

FactoryGirl.define do 
  factory :building do
    name "cannon"
    factory :building_with_bbi do
       name "cannon"
    end
  end
end

building = build_stubbed(:building)
building.building_basic_info
# => nil... but I want it to return the associated building_basic_info object

Any help is greatly appreciated.

like image 895
thedanotto Avatar asked Oct 15 '25 10:10

thedanotto


1 Answers

FactoryGirl.define do 
  factory :building do
    name "cannon"
    association :building_basic_info
  end

  factory :building_basic_info do
    name "cannon"
  end
end
like image 136
house9 Avatar answered Oct 17 '25 00:10

house9