【问题标题】:Fetch all rows that join via a list of values in Rails获取通过 Rails 中的值列表连接的所有行
【发布时间】:2020-03-17 12:56:59
【问题描述】:

我有两个表(模型):

  1. 学生
  2. 课程

它们都通过一个名为course_enrollments的表连接

在 Rails 中,它们是这样设置的:

Student.rb:
has_many :courses, through: course_enrollments

Course.rb:
has_many :students, through: course_entrollments

CourseEntrollment.rb:
belongs_to :student, foreign_key...
belongs_to :course, foreign_key..

我想从特定的课程列表中获取所有参加所有课程的学生,如下所示:

courses_list = current_professor.courses_teaching
student_list = Student.eager_load(:some_table_I_have_to_load).join_with_all_courses(courses_list).order(sort_attributes).paginate....

我的问题是我该怎么做?我在 SQL 方面不太强,并且正在努力弄清楚我需要什么。 我想我需要在 order 之前添加某种连接或 where 子句,但我在弄清楚什么以及如何正确执行它时遇到了一些困难

非常感谢!

【问题讨论】:

    标签: ruby-on-rails orm rails-activerecord


    【解决方案1】:

    如果courses_list 是一个关系。做起来很简单:

    student_list = Student.joins(:course_enrollments).where(course_enrollments: { course_id: courses_list.ids })
    

    【讨论】:

    • 酷,是的,这看起来就是我所缺少的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 2016-10-26
    • 2015-07-19
    • 1970-01-01
    • 2011-11-17
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多