[英]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.