繁体   English   中英

如何在Ruby on Rails中设置关联?

[英]How to set up associations in Ruby on Rails?

我正在构建用于实践的示例应用程序,无法确定组织模型和关联的最佳方法。 因此,让我们说我有3个模型:

  1. 学校
  2. 班级
  3. 学生们

我想要:

  • 学校有很多班
  • 班上有很多学生
  • 属于学校的课程
  • 学生将被许多不同学校的许多班录取

联想让我头晕,我不确定该使用哪个。 帮助将不胜感激。

您的模型应如下所示:

class School < ActiveRecord::Base
  has_many :classes
  has_many :students, :through => :classes
end

class Class < ActiveRecord::Base
  belongs_to :school
  has_and_belongs_to_many :students
end

class Student < ActiveRecord::Base
  has_and_belongs_to_many :classes
end

确保您的学生表和班级表分别具有class_idschool_id列。

另外,Class是Rails中保留字 ,因此可能会引起问题(您可能必须使用其他名称)

class重命名为course ,因为班级名称Class已经被使用。 诸如enrollments等加入课程将处理您的多对多课程学生关系。

class School
  has_many :courses
end

class Course
  belongs_to :school
  has_many :enrollments
  has_many :students, :through => :enrollments
end

class Student
  has_many :enrollments
  has_many :courses, :through => :enrollments
end

class Enrollment
  belongs_to :course
  belongs_to :student
end    

尽管乍一看似乎学生应该直接属于班级,但班级并不是真正的“ has_and_belongs_to_many”替代。 为此,我将使用“注册”。 (请注意,在rails 3.1中,您现在可以进行嵌套的:through调用。)

与以前的评论者相比,这是一个稍微高级的实现:

class School << ActiveRecord::Base
  has_many :academic_classes
  has_many :enrollments, :through => :academic_classes
  has_many :students, :through => :enrollments, :uniq => true
end

class AcademicClass << ActiveRecord::Base
  belongs_to :school
  has_many :enrollments
end

class Enrollment << ActiveRecord::Base
  belongs_to :academic_class
  belongs_to :student
end

class Student << ActiveRecord::Base
  has_many :enrollments
  has_many :academic_classes, :through => :enrollments
  has_many :schools, :through => :academic_classes, :uniq => true
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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