简体   繁体   中英

FactoryGirl association with different name

I have the following associations

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

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

The Attendance table has attendee_id and training_id .

Now, How can I create a valid Attendance with FactoryGirl?

Currently, I have the following code

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

But I get

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

I have also tried

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

With the same outcome.

Thanks for your help (or being polite is not allowed on SO???).

As you are probably aware FactoryGirl uses the symbol to infer what the class is, however when you are creating another factory with a different symbol for the same model you will need to tell FactoryGirl what the class to use is:

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

or can manually assign the relation (for example if you didn't want employee instance to be saved to database at this point):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM