【问题标题】:Should this has_many :through relationship be polymorphic or not?这个 has_many :through 关系是否应该是多态的?
【发布时间】:2015-03-10 02:27:21
【问题描述】:

我通过has_many :throughTeachersClassrooms 设置了多对多关系:

class Teacher < ActiveRecord::Base
  has_many :classrooms, :through => :classroom_memberships
end

class Classroom < ActiveRecord::Base
  has_many :students
  has_many :teachers, :through => :classroom_memberships
end

class ClassroomMemberships < ActiveRecord::Base
  belongs_to :teacher
  belongs_to :classroom
end

目前Students只能属于一个Classroom

class Student < ActiveRecord::Base
  belongs_to :classroom
end

现在我需要跟踪学生的历史课堂成员资格,为课堂创建第二个多对多关系。因此,虽然一个学生一次只能属于一个教室,但我需要知道去年学生 A 属于 B 教室。

我认为我有两个可行的选择:

1.) 将classroom_memberships 关联设为多态,这样我就有了classroomable_idclassroomable_type,它们将指向老师或学生。

2.) 简化事情并向 ClassroomMemberships 添加另一个名为 student_id 的外键,在这种情况下,对于给定的行,student_idteacher_id 都会有一个值。

哪个是更好的选择?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    我可能会走:

    class Course < ActiveRecord::Base
      # like "MATH 100"
      has_many :sections
      has_many :teachers, :through => :sections
    end
    
    class Term < ActiveRecord::Base
      # like "Fall 2015"
      has_many :sections
    end
    
    class Teacher < ActiveRecord::Base
      has_many :sections
      has_many :courses, :through => :sections
    end
    
    class Section < ActiveRecord::Base
      # a course, in a term, taught by a teacher, with registered students
      belongs_to :term
      belongs_to :course
      belongs_to :teacher
      has_many :registrations
      has_many :students, :through => :registrations
    end
    
    class Registration < ActiveRecord::Base
      # a student in a specific section
      belongs_to :section
      belongs_to :student 
    end
    
    class Student < ActiveRecord::Base
      # a student's registrations are their course history
      has_many :registrations
      has_many :sections, through :registrations
    end
    

    首先,因为这是一个相当基本的教育系统建模。

    【讨论】:

      【解决方案2】:

      听起来您可能想要一个 ClassroomMembershipHistory 模型。

      类似

      class ClassroomMembershipHistory < ActiveRecord::Base
        belongs_to :student
        belongs_to :classroom
      end
      

      带有year 属性,但存储起来最容易查询您的用例。

      【讨论】:

      • 嗯,但是你会让引用学生/教师多态的键吗?还是要添加两个键(parent_idteacher_id)?
      • 您还需要教师的历史课堂数据吗?您的问题表明只有学生需要记录其成员资格。
      • 没关系。 ClassroomMemberships 表可以包含给定教师的多行,我可以添加元数据以包括成员资格是否是历史的。这个问题真的归结为我是否应该去多态。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 2010-12-13
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多