[英]How to set up associations in Ruby on Rails?
我正在构建用于实践的示例应用程序,无法确定组织模型和关联的最佳方法。 因此,让我们说我有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_id
和school_id
列。
将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.