Get two associations within a Factory to share another association

后端 未结 6 1713
情书的邮戳
情书的邮戳 2021-02-12 14:57

I\'ve got these 5 models: Guardian, Student, Relationship, RelationshipType and School. Between them, I\'ve got these associations

class Guardian < ActiveReco         


        
6条回答
  •  名媛妹妹
    2021-02-12 15:34

    Extending on nitsas' solution, you can abuse @overrides to check whether the guardian or student association have been overridden, and use the school association from the guardian/student. This allows you to override not only the school, but also just the guardian or just the student.

    Unfortunately, this relies on instance variables, not public API. Future updates could very well break your factories.

    factory :relationship do
      guardian { create(:guardian, school: school) }
      student  { create(:student,  school: school) }
    
      transient do
        school do
          if @overrides.key?(:guardian)
            guardian.school
          elsif @overrides.key?(:student)
            student.school
          else
            create(:school)
          end
        end
      end
    end
    

提交回复
热议问题