获取特定类中的所有学生

mnemlml8  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(291)

我使用的是rails,我的模型描述如下:
类别.rb:

has_many :class_registrations

班级注册.rb:

belongs_to :class
belongs_to :student

学生.rb:

has_many :class_registrations

现在我怎样才能得到一个特定班级的所有学生名单呢 registrations.rb: 文件。

72qzrwbm

72qzrwbm1#

最好的方法是在类模型中添加一个具有多个关联的类

has_many :class_registrations
has_many :students, through: :class_registrations

你可以访问特定班级的所有学生

@class = Class.first
@class.students

# return all student of the first class

请记住,在rails中,您可以从任何模型或控制器访问所有模型,您可以创建一个类或示例方法,允许您从类注册访问类中的所有学生,但我不建议这样做,最好使用控制器或视图中需要的关联。
例如,如果您找到一个示例方法来获取班级注册中一个学生的所有同伴,您可以在班级注册.rb中定义一个方法

def companions 
    Student.where("id = ?", self.student_id)
  end
def students_of_class(class_id)    
  class = Class.find(class_id)   
  class.students   
end

相关问题