2016-11-14 43 views
2

FactoryGirl協會,我有以下的關聯用不同的名字

class Training < ApplicationRecord 
    has_many :attendances 
    has_many :attendees, through: :attendances 
end 

class Attendance < ApplicationRecord 
    belongs_to :training 
    belongs_to :attendee, class_name: 'Employee' 

考勤表有attendee_idtraining_id

現在,我如何使用FactoryGirl創建有效的Attendance

目前,我有以下的代碼

FactoryGirl.define do 
    factory :attendance do 
    training 
    attendee 
    end 
end 

FactoryGirl.define do 
    factory :employee, aliases: [:attendee] do 
    sequence(:full_name) { |n| "John Doe#{n}" } 
    department 
    end 
end 

,但我得到

NoMethodError: 
     undefined method `employee=' for #<Attendance:0x007f83b163b8e8> 

我也曾嘗試

FactoryGirl.define do 
    factory :attendance do 
    training 
    association :attendee, factory: :employee 
    end 
end 

有了相同的結果。

感謝您的幫助(或有禮貌是不允許的SO ???)。

回答

4

正如你可能知道FactoryGirl使用符號來推斷類是什麼,但是當你創建了另一家工廠與同型號不同的符號,你需要告訴FactoryGirl如何使用類:

FactoryGirl.define do 
    factory :attendance do 
    training = { FactoryGirl.create(:training) } 
    attendee = { FactoryGirl.create(:employee) } 
    end 
end 

FactoryGirl.define do 
    factory :employee, class: Attendee do 
    sequence(:full_name) { |n| "John Doe#{n}" } 
    department 
    end 
end 

或可以手動分配的關係(例如,如果你不想員工實例在這一點上保存到數據庫):

FactoryGirl.build(:attendance, attendee: FactoryGirl.build(:employee))