簡體   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