gpt4 book ai didi

ruby-on-rails - 具有不同名称的 FactoryGirl 协会

转载 作者:行者123 更新时间:2023-12-03 21:29:24 27 4
gpt4 key购买 nike

我有以下关联

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 .

现在,我如何创建一个有效的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com