我有以下关联
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
.现在,我如何创建一个有效的
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 上不允许有礼貌???)。
最佳答案
您可能知道 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))
关于ruby-on-rails - 具有不同名称的 FactoryGirl 协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585384/