我有以下协会
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_id
和training_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上不允许礼貌)。
答案 0 :(得分: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))