Get two associations within a Factory to share another association

后端 未结 6 1651
情书的邮戳
情书的邮戳 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:44

    This isn't really an answer you are seeking, but it seems that the difficulty in creating this association is suggesting that the table design may need to be adjusted.

    Asking the question What if the user changes school?, the school on both the Student and Guardian needs to be updated, otherwise, the models get out of sync.

    I put forward that a student, a guardian, and a school, all have a relationship together. If a student changes school, a new Relationship is created for the new school. As a nice side effect this enables a history to exist of where the student has been schooled.

    The belongs_to associations would be removed from Student and Guardian, and moved to Relationship instead.

    The factory can then be changed to look like this:

    factory :relationship do
      school
      student
      guardian
      relationship_type
    end
    

    This can then be used in the following ways:

    # use the default relationship which creates the default associations
    relationship = Factory.create :relationship
    school = relationship.school
    student = relationship.student
    guardian = relationship.guardian
    
    # create a relationship with a guardian that has two charges at the same school
    school = Factory.create :school, name: 'Custom school'
    guardian = Factory.create :guardian
    relation1 = Factory.create :relationship, school: school, guardian: guardian
    relation2 = Factory.create :relationship, school: school, guardian: guardian
    student1 = relation1.student
    student2 = relation2.student
    

提交回复
热议问题