【问题标题】:get all students from a specific class获取特定班级的所有学生
【发布时间】:2020-07-02 06:04:34
【问题描述】:

我正在使用 Rails,我的模型被描述为:

class.rb:

has_many :class_registrations

类注册.rb:

belongs_to :class
belongs_to :student

学生.rb:

has_many :class_registrations

现在如何在registrations.rb: 文件中获取特定班级的所有学生列表。

【问题讨论】:

    标签: sql ruby-on-rails activerecord associations


    【解决方案1】:

    最好的方法是在 Class 模型中通过关联添加一个 has many

    has_many :class_registrations
    has_many :students, through: :class_registrations
    

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

    @class = Class.first
    @class.students
    #return all student of the first class
    

    请记住,在 Rails 中,您可以从任何模型或控制器访问所有模型,您可以创建一个类或实例方法,允许您从 class_registrations 访问一个班级中的所有学生,但我不推荐这样做,它是如果您使用需要它的控制器或视图中的关联会更好。

    例如,如果您找到一个实例方法来获取班级注册中学生的所有同伴,您可以在 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
    

    【讨论】:

    • 我想知道一个特定班级ID的所有学生
    • class 不包含学生,但 class_registrations 有两个字段,即 class_id 和 student_id。
    • 如果你发现像类方法一样使用,例如:ClassRegistrations.students_of_class(1) add self.在默认方法中:def self.students_of_class(class_id)
    • has_many :students, through: :class_registrations这个关联more info
    • 我可以这样使用吗:class_student= class_registration.where(class_id: 'user.id'); class_student.student_id;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多