从特定 class 获取所有学生
get all students from a specific class
我正在使用 rails,我的模型被描述为:
class.rb:
has_many :class_registrations
class registrations.rb:
belongs_to :class
belongs_to :student
student.rb:
has_many :class_registrations
现在如何获取 registrations.rb:
文件中特定 class 的所有学生列表。
最好的方法是在 Class 模型中添加一个有很多直通关联
has_many :class_registrations
has_many :students, through: :class_registrations
并且您可以访问特定 class
的所有学生
@class = Class.first
@class.students
#return all student of the first class
请记住,在 rails 中,您可以从任何模型或控制器访问所有模型,您可以创建一个 class 或实例方法,允许您访问 [=25] 中的所有学生=] 来自 class_registrations 但我不推荐它,如果您使用来自需要它的控制器或视图的关联会更好。
例如,如果你在class regitration中找到一个实例方法来获取一个学生的所有同伴,你可以在class_registrations.rb
中定义一个方法
def companions
Student.where("id = ?", self.student_id)
end
def students_of_class(class_id)
class = Class.find(class_id)
class.students
end
我正在使用 rails,我的模型被描述为:
class.rb:
has_many :class_registrations
class registrations.rb:
belongs_to :class
belongs_to :student
student.rb:
has_many :class_registrations
现在如何获取 registrations.rb:
文件中特定 class 的所有学生列表。
最好的方法是在 Class 模型中添加一个有很多直通关联
has_many :class_registrations
has_many :students, through: :class_registrations
并且您可以访问特定 class
的所有学生@class = Class.first
@class.students
#return all student of the first class
请记住,在 rails 中,您可以从任何模型或控制器访问所有模型,您可以创建一个 class 或实例方法,允许您访问 [=25] 中的所有学生=] 来自 class_registrations 但我不推荐它,如果您使用来自需要它的控制器或视图的关联会更好。
例如,如果你在class regitration中找到一个实例方法来获取一个学生的所有同伴,你可以在class_registrations.rb
中定义一个方法 def companions
Student.where("id = ?", self.student_id)
end
def students_of_class(class_id)
class = Class.find(class_id)
class.students
end