从几个模型中查询值

时间:2018-12-13 10:02:26

标签: ruby-on-rails

我有一个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
  ...

2 个答案:

答案 0 :(得分:1)

尝试:

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

它接受@courses列表中的每门课程,并获得该课程的课程列表。

答案 1 :(得分:1)

class Student < ApplicationRecord
  has_many :courses

  def active_lessions
    Lession.joins(course: :students).where(students: {id: self.id})
  end
end

通过这种方式,您可以直接获取current_user的所有活动课程

current_student.active_lessions