ruby-on-rails - 从多个模型中查询值
问题描述
我有一个Course
和Lesson
模型。课程有几节课。我想找到当前登录学生的所有课程以生成某种时间表。
我有一个方法可以返回该学生正在学习的所有课程。现在我想从所有这些课程中获得所有课程@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
...
解决方案
尝试:
@lessons = @courses.flat_map(&:lessons)
它@courses
获取列表中的每门课程并获取该课程的课程列表。
推荐阅读
- flutter - Flutter web TextField 不显示写在键盘上的文本
- python - 一种能够消除 N 个障碍物的星型算法
- pic - 无法在 MPLABX (PKOB) 上使用 Curiosity HPC,如何让它在当前 IDE 上工作?
- html - 小图标图像添加到 span 类里面
- 标签?
- html - Italic tag not being formatted in Github Pages
- python - 使用 Python 调用 JSON API
- firebase - 如何将 Google App Engine 与 Firebase 结合使用
- php - Symfony 翻译忽略参数中的花括号
- wordpress - 如何在 wordpress 主题中包含 json 清单文件
- python - “while”循环未按预期运行