我正在为练习构建一个示例应用,并且无法确定组织模型和关联的最佳方式。所以,我们只说我有3个模型:
我想:
协会让我头晕目眩,我不确定使用哪些。非常感谢帮助。
答案 0 :(得分:2)
您的模型应如下所示:
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是reserved word in Rails,因此可能会导致问题(您可能需要使用其他名称)
答案 1 :(得分:2)
将class
重命名为course
,因为已经取消了班级名称Class
。联接类(例如enrollments
)可以处理您的多对多课程&lt; =&gt;学生关系。
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
答案 2 :(得分:1)
虽然第一次看到学生应该直接属于班级,但班级并不是真正的“has_and_belongs_to_many”替代品。为此我会使用“注册”。 (注意使用rails 3.1,您现在可以嵌套:通过调用。)
这是一个比之前的评论者更高级的实现:
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