【问题标题】:how to model a many-to-many relationship, associated with a has-many relationship rails如何建模与多对多关系关联的多对多关系
【发布时间】:2017-08-25 22:32:38
【问题描述】:

我有以下场景:

学生属于_to并且有很多课程,
课程有_许多课程
课程属于_课程

这是我目前的模型:

class Student < ActiveRecord::Base
  has_many  :studentcourses
  has_many  :courses, :through => :studentcourses
end

class StudentCourse < ActiveRecord::Base //join table
  belongs_to :course
  belongs_to :student
end


class Course < ActiveRecord::Base
  has_many  :studentcourses
  has_many  :students, :through => :studentcourses
  has_many  :lessons
end

class Lesson < ActiveRecord::Base
  belongs_to :course
end

因此,学生被分配到一门或多门课程,并且课程有许多课程。 我如何对其建模,以便我可以检索一个学生的所有课程以及属于该课程的所有学生的所有课程?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    使用原生has_and_belongs_to_many关系并指定比StudentLessons通过Courses

    class Student < ActiveRecord::Base
      has_and_belongs_to_many :courses
      has_many :lessons, through: :courses
    end
    
    class Course < ActiveRecord::Base
      has_and_belongs_to_many :students
      has_many :lessons
    end
    
    class Lesson < ActiveRecord::Base
      belongs_to :course
    end
    

    这是 HABTM 关系的迁移:

    class CreateStudentsCourses < ActiveRecord::Migration
      create_table :students_courses, id: false do |t|
        t.belongs_to :student, index: true
        t.belongs_to :course, index: true
      end
    end
    

    这样你可以得到所有学生的课程@some_student.lessons,但是很遗憾你不能得到@some_lesson.students,因为没有belongs_to :through关联,但是你可以委托students方法:

    class Lesson < ActiveRecord::Base
      belongs_to :course
      delegate :students, to: :course
    end
    

    这样,调用@lesson.students,方法students 将在关联的Course 上调用,该Course 已定义此方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多