首页 > 解决方案 > 从多个模型中查询值

问题描述

我有一个CourseLesson模型。课程有几节课。我想找到当前登录学生的所有课程以生成某种时间表。

我有一个方法可以返回该学生正在学习的所有课程。现在我想从所有这些课程中获得所有课程@courses@lessons例如:

def index
    @courses = current_student.find_courses
    @lessons = @courses.lessons
end

有可能在一条线上以某种方式简单吗?

find_courses 方法实现如下:

def find_courses
    Course.where("id IN (?)", StudentAssignment.select("course_id").where('student_id == (?)', self.id))
  end

模型:

class Student < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :student_assignments
  has_many :courses, :through => :student_assignments
  ....

class Lesson < ApplicationRecord
      belongs_to :room
      belongs_to :teacher
      belongs_to :course
      ....

class Course < ApplicationRecord
  has_many :lessons, dependent: :destroy
  has_many :teacher_assignments
  has_many :teachers, :through => :teacher_assignments
  has_many :student_assignments
  has_many :students, :through => :student_assignments
  ...

标签: ruby-on-rails

解决方案


尝试:

@lessons = @courses.flat_map(&:lessons)

@courses获取列表中的每门课程并获取该课程的课程列表。


推荐阅读